gpt4 book ai didi

objective-c - NSComparisonResult,如何比较一个 searchText 和多个字符串?

转载 作者:行者123 更新时间:2023-12-02 05:14:25 26 4
gpt4 key购买 nike

我正在使用此代码在我的表格 View 中进行搜索:

for (Actor *actorz in arr)
{
NSComparisonResult result = [actorz.actorNaam compare:searchText options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch) range:[actorz.actorNaam rangeOfString:searchText options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch)]];
if (result == NSOrderedSame)
{
[self.filteredListContent addObject:actorz];
}
}

现在我想知道如何不仅可以将 searchText 与 actorz.actorNaam 进行比较,还可以将其与 actorz.actorBeschrijving 进行比较?所以我想将 searchText 与两个字符串进行比较..

最佳答案

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

关于objective-c - NSComparisonResult,如何比较一个 searchText 和多个字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14893765/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com