我是一个真正的初学者,这是我的第一篇文章,所以请耐心等待......我有一个包含一系列AddressCards的AddressBook。 'book'是一个NSMutableArray。我想查找一个字符串,让它从AddressBook返回一个匹配数组。例如,搜索'fr'会返回'freddy','frank','franklin'。我的问题在这里是什么?谢谢你的帮助。
- (NSMutableArray *)lookup:(NSString *)theName {
NSMutableArray *newArray = [[NSMutableArray alloc]init];
AddressCard *nextCard;
for(nextCard in book) {
if ([nextCard.name rangeOfString:theName].location != NSNotFound) {
[newArray addObject:nextCard];
}
}
if (nextCard) {
return newArray;
} else {
return nil;
}
}
答案 0 :(得分:1)
这应该有效:
- (NSArray *)lookup:(NSString *)theName {
NSMutableArray *newArray = [[NSMutableArray alloc] init];
for(AddressCard *card in book) {
if ([card.name rangeOfString:theName].location != NSNotFound) {
[newArray addObject:card];
}
}
return [newArray count] ? [newArray copy] : nil;
}
您也可以使用-filteredArrayUsingPredicate:
- (NSArray *)lookup:(NSString *)theName {
NSArray *filteredCardsMatchingName = [books filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"SELF CONTAINS[cd] %@", theName]];
return [filteredCardsMatchingName count] ? filteredCardsMatchingName : nil;
}