Obj-C,iOS,有人可以解释这个NSMutableArray代码并建议我如何对名称进行排序?

时间:2011-05-30 11:17:53

标签: iphone objective-c cocoa nsmutablearray

有人可以详细解释这段代码并建议我如何对名称进行排序吗?

- (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];
}

1 个答案:

答案 0 :(得分:4)

- (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
}

我希望这一切都有道理,我尽力评论它;)

祝你好运。