Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 413
Ravi Avatar asked Sep 13 '11 04:09

Ravi


People also ask

What is an NSArray?

An object representing a static ordered collection, for use instead of an Array constant in cases that require reference semantics.

What is NSArray Swift?

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 .

What is difference between NSArray and NSMutableArray?

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.


3 Answers

You can do it like,

NSArray* yourArray = [NSArray arrayWithObjects: @"Str1", @"Str2", @"Str3", nil];
if ( [yourArray containsObject: yourStringToFind] ) {
    // do found
} else {
    // do not found
}
like image 70
Janak Nirmal Avatar answered Oct 31 '22 22:10

Janak Nirmal


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]);   
like image 32
bryanmac Avatar answered Oct 31 '22 20:10

bryanmac


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
like image 35
Steven Fisher Avatar answered Oct 31 '22 21:10

Steven Fisher