Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to search through a NSMutableArray

I have a NSMutableArray that I need to search for a string and return the key in the array where the string was found. So for example if I'm searching "ipod" and it's the 4th in the array, it would return 3 or whatever position the string is in. What's the best way to do this?

like image 405
Raphael Caixeta Avatar asked Apr 09 '10 18:04

Raphael Caixeta


People also ask

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.

What is NSMutableArray?

The NSMutableArray class declares the programmatic interface to objects that manage a modifiable array of objects. This class adds insertion and deletion operations to the basic array-handling behavior inherited from NSArray . NSMutableArray is “toll-free bridged” with its Core Foundation counterpart, CFMutableArray .


2 Answers

return [theArray indexOfObject:@"ipod"];

Reference: http://developer.apple.com/iphone/library/documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/NSArray.html#//apple_ref/occ/instm/NSArray/indexOfObject:.

Note that NSMutableArray inherits from NSArray, so any NSArray methods can be used on NSMutableArray too.

like image 131
kennytm Avatar answered Nov 11 '22 09:11

kennytm


Again from the documentation: Index of Object Passing test

You'll have to write a code block that tests for the substring in each object: NSString rangeOfString: options:

Then you'll get the index of the object with the substring. You'll need to run the string search again for your result, but that should get you what you are after.

like image 35
Luke Avatar answered Nov 11 '22 10:11

Luke