How might I check if a particular NSString is present in an NSArray?

自作多情 提交于 2019-12-03 18:00:38

问题


How might I check if a particular NSString is presnet in an NSArray?


回答1:


You can do it like,

NSArray* yourArray = [NSArray arrayWithObjects: @"Str1", @"Str2", @"Str3", nil];
if ( [yourArray containsObject: yourStringToFind] ) {
    // do found
} else {
    // do not found
}



回答2:


Iterating or containsObject are order n ways to find.

If you want constant time lookup, you can also maintain a hash table like NSSet or NSHashTable but that increases space but saves time.

NSArray* strings = [NSArray arrayWithObjects: @"one", @"two", @"three", nil];
NSSet *set = [NSSet setWithArray:strings];

NSString* stringToFind = @"two";
NSLog(@"array contains: %d", (int)[strings containsObject:stringToFind]);
NSLog(@"set contains: %d", (int)[set containsObject:stringToFind]);   



回答3:


Depends on your needs. Either indexOfObject if you care about equality (most likely), or indexOfObjectIdenticalTo if you care it's actually the same object (i.e. same address).

Source:

  • NSArray Class Reference


来源:https://stackoverflow.com/questions/7396919/how-might-i-check-if-a-particular-nsstring-is-present-in-an-nsarray

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!