问题描述
|
有人可以详细解释此代码并建议我如何对名称进行排序?
- (void)handleSearchForTerm:(Nsstring *)searchTerm {
selectButton.enabled = NO;
NSMutableArray *sectionsToRemove = [[NSMutableArray alloc] init];
[self resetSearch];
for (Nsstring *key in self.keys) {
NSMutableArray *array = [Categories valueForKey:key];
NSMutableArray *toRemove = [[NSMutableArray alloc] init];
for (Nsstring *name in array) {
if ([name rangeOfString:searchTerm
options:NSCaseInsensitiveSearch].location == NSNotFound)
[toRemove addobject:name];
}
if ([array count] == [toRemove count])
[sectionsToRemove addobject:key];
[array removeObjectsInArray:toRemove];
[toRemove release];
}
[self.keys removeObjectsInArray:sectionsToRemove];
[sectionsToRemove release];
[table reloadData];
}
解决方法
- (void)handleSearchForTerm:(NSString *)searchTerm {
selectButton.enabled = NO;
NSMutableArray *sectionsToRemove = [[NSMutableArray alloc] init]; //creating an mutable array,which can be altered in progress.
[self resetSearch]; //calling some other method not displayed in the code here
for (NSString *key in self.keys) { //for each key,NSMutableArray *array = [Categories valueForKey:key]; //you get the key\'s category
NSMutableArray *toRemove = [[NSMutableArray alloc] init]; //and initialize the array for items you wish to remove
for (NSString *name in array) { //then,for each name
if ([name rangeOfString:searchTerm options:NSCaseInsensitiveSearch].location == NSNotFound)
[toRemove addObject:name];
//you check if the name is in range of the searchterm,with which you call this function
//if you don\'t find it,you add it to the removal list
}
if ([array count] == [toRemove count])
[sectionsToRemove addObject:key]; //if you haven\'t found any name,it means you\'ve added all the names in the toRemove array
[array removeObjectsInArray:toRemove]; //that means the count of both arrays are the same
[toRemove release]; //so you remove that section entirely,since there is no result there
}
[self.keys removeObjectsInArray:sectionsToRemove]; //you remove all the keys which aren\'t found
[sectionsToRemove release]; //leaving you the keys which are found
[table reloadData]; //you reload the table with the found results only
}
我希望一切都有意义,我尽了最大的努力来评论它;)
祝好运。