如果未找到该字符串,则NSString
返回一个NSRange
位置设置为的搜索方法。NSNotFound
因此,您可以通过验证结果位置是否不是 来检查是否找到了字符串NSNotFound
。这听起来可能有点倒退,但逻辑是可靠的(可以说是两个否定)。
NSRange nameResult = [actorz.actorNaam rangeOfString:searchText options:NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch];
NSRange descrResult = [actorz.actorBeschrijving rangeOfString:searchText options:NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch];
if ( nameResult.location != NSNotFound || descrResult.location != NSNotFound ) {
[self.filteredListContent addObject:actorz];
}
请注意,此代码段将查找包含搜索字符串的名称,而不仅仅是名称相等。您可能想使用原始代码进行更改。您当然必须删除 nameResult,因为它是多余的:
NSComparisonResult result = [actorz.actorNaam compare:searchText options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch) range:[actorz.actorNaam rangeOfString:searchText options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch)]];
NSRange descrResult = [actorz.actorBeschrijving rangeOfString:searchText options:NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch];
if ( result == NSOrderedSame || descrResult.location != NSNotFound ) {
[self.filteredListContent addObject:actorz];
}
但是,有一种更简单的方法。考虑使用谓词:
NSPredicate *actorPred = [NSPredicate predicateWithFormat:@"actorNaam contains[cd] %@ OR actorBeschrijving contains[cd] %@", searchText, searchText];
self.filteredListContent = [arr filteredArrayUsingPredicate:actorPred];