Fervus
Fervus

Reputation: 720

how do I get the index at which an Object has been added to an NSMutableArray?

I'm adding an object to a NSMutableArray like this:

[array addObject:myObject];

I now want to send a reference to my delegates of the Array Index where this object was added. Is there an easy way to find out the index where my object was added in the array so that later I can call

[array objectAtIndex:index] 

to get a reference back for it?

Thanks!

Upvotes: 1

Views: 81

Answers (6)

Caleb
Caleb

Reputation: 125007

Rather than passing the index of an object (which could be incorrect) to your delegate, pass a reference to the object itself. If the delegate needs the index of the object in the array, it can figure it out itself using -indexOfObject: as Antonio MG describes. The index of any given object in a mutable array can change as objects are added, inserted, and deleted. Counting on indices to remain valid over any period of time is like leaving a jelly sandwich on the counter -- it's sure to attract bugs.

Upvotes: 2

Francesco
Francesco

Reputation: 1848

If you call addObject you always add the object at the end (so count - 1). You can use "insertObject:atIndex:" to specify an index. For your question: indexOfObject:

Upvotes: 0

Jason Coco
Jason Coco

Reputation: 78363

You need to serialize access to a mutable array and -addObject: always adds the object to the end of the array. Given those two assertions, you know the index of the next added object will always be the current length of the array. So the following will hold true:

NSUInteger nextIndex = [array count];
[array addObject:myObject];
// you can now tell your delegates that nextIndex is the index of myObject

Upvotes: 1

Kai Huppmann
Kai Huppmann

Reputation: 10775

Direct after adding the object's index is array.count -1 .

Upvotes: -1

He Shiming
He Shiming

Reputation: 5819

The latest added object should be at [array count] - 1 index. You can always rely on "count - 1" scheme to determine the last index.

Upvotes: 0

Antonio MG
Antonio MG

Reputation: 20410

Use this method for that:

index = [animalOptions indexOfObject:myObject];

Upvotes: 0

Related Questions