tags:

views:

83

answers:

2

ruby code(irb)

irb(main):001:0> ary = ["AAA", "BBB", "CCC"]
=> ["AAA", "BBB", "CCC"]
irb(main):003:0> ary.index("AAA")
=> 0
irb(main):004:0> ary.index("BBB")
=> 1
irb(main):005:0> ary.index("CCC")
=> 2
irb(main):006:0> ary.index("DDD")
=> nil

I want to do same in objective-c(NSMutableArray).

A: 

Read Apple’s documentation for NSArray and NSMutableArray.

Chris Suter
+2  A: 
NSMutableArray *ary = [NSMutableArray arrayWithObjects:@"AAA",@"BBB",@"CCC",nil];
NSLog([ary description]);
NSInteger ndx = [ary indexOfObjectIdenticalTo:@"AAA"];
NSLog(@"%i",ndx);
ndx = [ary indexOfObjectIdenticalTo:@"BBB"];
NSLog(@"%i",ndx);
ndx = [ary indexOfObjectIdenticalTo:@"CCC"];
NSLog(@"%i",ndx);
ndx = [ary indexOfObjectIdenticalTo:@"DDD"];
NSLog(@"%i",ndx);

Cocoa methods are all pretty self explanatory, so skimming the headers can help you solve almost any problem.

EDIT: changed from NSArray to NSMutableArray, added note:

Note: the last method returns -1, not nil.

Kenny Winker
You’ve used indexOfObjectIdenticalTo. Fortunately, due to compiler optimisations, that will work in the example you’ve provided, but it’s not guaranteed to do so. You should be using -indexOfObject:.Also the last case returns NSNotFound, which is not -1.Lastly, you should be using NSUInteger, not NSInteger and if I wanted to be really picky, I’d point out that you’d use the %lu format specifier and cast ndx to unsigned long which, frankly, is pretty ugly, but you can blame Apple for that one.
Chris Suter
Whoops! Thanks for the corrections chris. I mixed up which method matches objects with the exact same address in memory, and the one that matches objects with the exact same values. Thought i'd gotten it right because it executed correctly (if it compiles: ship it!).
Kenny Winker