开发者

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

开发者 https://www.devze.com 2023-04-04 05:25 出处:网络
How might I check if a particular NSString is presnet in an NSArra开发者_如何学JAVAy?You can do it like,

How might I check if a particular NSString is presnet in an NSArra开发者_如何学JAVAy?


You can do it like,

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


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


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
0

精彩评论

暂无评论...
验证码 换一张
取 消