views:

20

answers:

2
NSMutableArray *myArray = [[NSMutableArray alloc] init];
MyClass *obj1 = [[MyClass alloc] init];
[myArray addObject: obj1];

How to clean the old obj1 reference here, if I want to reuse the variable name. Without destroying anything in the array.

obj1 = nil 

OR

[obj1 release];

// What is the differences?

obj1 = [[MyClass alloc] init];
[myArray addObject: obj1];

........... Continue using obj1 and add in array.

+2  A: 

Assigning nil to the variable has no effect. You need to call release to ensure that the old object gets properly cleaned up.

BTW, reusing variable names within a block a of code is usually a bad idea.

Marcelo Cantos
If I am going to add some sample constant object in the array, I am reluctant to use obj1, obj2 ... that's why. Thanks for the answer. 1up.
karim
Without knowing the details of your code, all I can say is that it isn't *always* a bad idea, just *usually*. Thanks for the vote. :-)
Marcelo Cantos
+1  A: 

When you add an object to array, array stores the variable address, so you can freely use your temporary variable(obj1) to create another object - the value in the array won't be destroyed.

But since array retains its elements for proper memory management you need to release obj1 after pushing it to array. So you need [obj1 release]; line

Vladimir