How might I check if a particular NSString is presnet in an NSArray?
An object representing a static ordered collection, for use instead of an Array constant in cases that require reference semantics.
NSArray is an immutable Objective C class, therefore it is a reference type in Swift and it is bridged to Array<AnyObject> . NSMutableArray is the mutable subclass of NSArray .
The primary difference between NSArray and NSMutableArray is that a mutable array can be changed/modified after it has been allocated and initialized, whereas an immutable array, NSArray , cannot.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With