Andrey Chernukha
Andrey Chernukha

Reputation: 21808

Difference in setting arrays

In my app i need to change content of one NSMutableArray constantly. I used this method

myArray = [NSArray arrayWithObjects:object1,object2,object3,nil];

I did it several times and all went fine until i noticed that when i quit the view the app crashes. I changed the way of setting content of myArray to:

[myArray setArray:[NSArray arrayWithObjects:object1,object2,object3,nil]];

and that was enough to stop crashes and everything to work just fine. But i'm just curious about what's going on there deep down inside that makes the app crash when using first method (and by the way why it crashes not immediately but only when i pop the view off the stack?) and affects nothing when using second one.

Upvotes: 0

Views: 42

Answers (1)

NSResponder
NSResponder

Reputation: 16861

In the first case, you're setting myArray to point to an autoreleased object. In the second case, you're telling myArray (presumably an existing NSMutableArray instance at that point) to replace whatever contents it has with the contents of another array.

You need to read up on the memory management rules.

Upvotes: 4

Related Questions