bbullis21
bbullis21

Reputation: 741

NSMutableArray - Get Arrays Index Integer By Searching With A String

I have been working with NSMutableArray and have had no problems retrieving an object from an array by using objectAtIndex:int. Rather then pulling an object out of the array by an integer is their a way to get the index position by searching the array with a string.

animalOptions = [[NSMutableArray alloc] init]; 
//Add items
[animalOptions addObject:@"Fish"];
[animalOptions addObject:@"Bear"];
[animalOptions addObject:@"Bird"];
[animalOptions addObject:@"Cow"];
[animalOptions addObject:@"Sheep"];

NSString * buttonTitle = [animalOptions objectAtIndex:1];
// RETURNS BEAR

int * objectIndex = [animalOptions object:@"Bear"];
// THIS IS WHAT I NEED HELP WITH, PULLING AN INDEX INTEGER WITH A STRING (ex: Bear)

Hopefully this makes sense, and there is an answer out there, I have been unable to research online and find anything through google or apple's class references.

Upvotes: 9

Views: 29795

Answers (2)

Alex Rozanski
Alex Rozanski

Reputation: 38005

You can use the indexOfObject: method from NSArray:

NSUInteger index = [animalOptions indexOfObject:@"Bear"];

If there are duplicate entries then the lowest index of that object is returned. For more information, take a look at the docs.

Upvotes: 34

Daniel
Daniel

Reputation: 22395

you can use [array indexOfObject:object] which will return the index of that object, now with the way you are wanting to do it, it might not w ork since the string you are specifing is not the actual string object in the array doing this however will def work

NSString * buttonTitle = [animalOptions objectAtIndex:1];// RETURNS BEARint 
objectIndex = [animalOptions indexOfObject:buttonTitle] //this will return 1

Upvotes: 0

Related Questions