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

前端 未结 3 485
执念已碎
执念已碎 2020-12-17 09:15

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

相关标签:
3条回答
  • 2020-12-17 09:46

    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]);   
    
    0 讨论(0)
  • 2020-12-17 09:53

    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 讨论(0)
  • 2020-12-17 09:59

    You can do it like,

    NSArray* yourArray = [NSArray arrayWithObjects: @"Str1", @"Str2", @"Str3", nil];
    if ( [yourArray containsObject: yourStringToFind] ) {
        // do found
    } else {
        // do not found
    }
    
    0 讨论(0)
提交回复
热议问题