John Baum
John Baum

Reputation: 3331

Creating a NSMutableArray to hold pointers

I am trying to create a mutable array in objetive c to hold references to objects. The objects in the array are regularly updated through user interaction and i want the array to automatically reflect changes made to the objects as they occur. Does anyone know if there is a way to do this? Perhaps store pointers to the objects instead of the objects themselves in the array? Any help would be much appreciated

Thanks in advance

Edit: I should mention that the objects are not exactly being updated in the strict sense of the word. They are being reinitialized. For ex if i had a controller:

MyController = [MyController alloc] initWith.....]]

the above call is made again with different init parameters.

Upvotes: 0

Views: 156

Answers (2)

Mario
Mario

Reputation: 4520

The array always stores the pointers.... It holds a strong reference to it or sends it a retain message (if using non ARC).

So

[myMutableArray addObject: anObject];

adds the pointer to it.

If you now change anObject's properties and access it later through the array, it will give you the pointer to just that object with the changes to its properties.

Edit:

No, if you alloc/init, you are creating a new object instance and allocate new memory for it on the heap (ie, it's another pointer to a new memory address). What exactly are you trying to accomplish? There sure is a way, if you provide a little more detail.

If you alloc/init the object with the same class, why not just create a method to change the object's properties:

Instead of

myObject = [[MyClass alloc] initWithParameter1: one parameter2: two];

You could create a method that changes these properties:

[myObject updateParameter1: anotherOne parameterTwo: anotherTwo];

And, of course, the advantage of a mutable array is, that you can change its contents, so like @Eli Gregory pointed out, you can replace an object with another one (or rather the pointers to it).

Upvotes: 4

esreli
esreli

Reputation: 5071

Because you want to point to a newly allocated and initialized object, you can't 'update' the pointer, what you can do is 'replace' the pointer with a new one at a certain index.

A method you could use to do this is:

- (void)replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject

so it would look something like:

NewViewController *new = [[NewViewController alloc] init..];
[myArray replaceObjectAtIndex:x withObject:new];

Upvotes: 0

Related Questions