Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question
add comment

2 Answers

up vote 19 down vote accepted

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.

share|improve this answer
 
Will this work with two different NSStrings -- the one in the array and the parameter being passed? Or is the comparison "deep"? –  fbrereto Sep 1 '09 at 17:15
 
Thank You! Amazingly quick response, This solved my question. –  bbullis21 Sep 1 '09 at 17:16
3  
Yes – equality is tested by sending an isEqual: message to the object. An NSString instance will return YES if the string values are equal, even if they are two different instances. –  Alex Rozanski Sep 1 '09 at 17:17
4  
You should use NSUInteger, not int, particularly if you intend to support 64-bit Mac OS X. –  Peter Hosey Sep 2 '09 at 0:39
 
This is great!! –  jxdwinter Mar 12 at 2:04
add comment

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
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.