Jos*_*osh 17 objective-c nsstring nsarray ios
我正在制作一个iOS应用程序,我需要弄清楚是否NSString
包含任何NSStrings
一个NSArray
.
Nic*_*ore 35
BOOL found=NO;
for (NSString *s in arrayOfStrings)
{
if ([stringToSearchWithin rangeOfString:s].location != NSNotFound) {
found = YES;
break;
}
}
Run Code Online (Sandbox Code Playgroud)
小智 14
对于您的用例来说,这可能是一个愚蠢的优化,但是根据您正在迭代的数组的大小,使用NSArray's
indexOfObjectWithOptions:passingTest:
方法可能会有所帮助/更高效.
使用此方法,您可以传递一些选项和包含测试的块.通过该NSEnumerationConcurrent
选项将允许您的块的评估同时在多个线程上发生,并可能加快速度.我重复使用了invariant的测试,但方式略有不同.该块在函数的实现中在函数上返回类似于"found"变量的BOOL."*stop = YES;" line表示迭代应该停止.
有关详细信息,请参阅NSArray参考文档.参考
NSArray *arrayOfStrings = ...;
NSString *stringToSearchWithin = ...";
NSUInteger index = [arrayOfStrings indexOfObjectWithOptions:NSEnumerationConcurrent
passingTest:^(id obj, NSUInteger idx, BOOL *stop)
{
NSString *s = (NSString *)obj;
if ([stringToSearchWithin rangeOfString:s].location != NSNotFound) {
*stop = YES;
return YES;
}
return NO;
}];
if (arrayOfStrings == nil || index == NSNotFound)
{
NSLog(@"The string does not contain any of the strings from the arrayOfStrings");
return;
}
NSLog(@"The string contains '%@' from the arrayOfStrings", [arrayOfStrings objectAtIndex:index]);
Run Code Online (Sandbox Code Playgroud)