Label
Label

Reputation: 33

Deleting elements of an NSMutableArray

I've been trying to fix a bug for really long and I could do with some suggestions. I have two NSMutableArrays tem and list. list is an arrayWithArrays, so every time I load data onto tem after finishing I say [list addObject: tem]; My code is such that, before adding a fresh set of data to tem, I delete all it's elements and begin adding elements again. However deleting the elements from tem results in them being deleted from list as well. What can I do to avoid it being deleted from list?

Upvotes: 0

Views: 772

Answers (1)

walkytalky
walkytalky

Reputation: 9543

Not sure what you mean by "'list' is an arrayWithArrays" -- if it's meant to be a standard method, it's wrong -- so you ought to clarify this. But answering what I think is your question:

addObject adds the object itself, ie just a pointer to your array tem. Both pointers still refer to the same NSArray instance, so anything you do via one will also be seen via the other. If this confuses you, you should read up on pointers.

If you actually want the objects in list to be grouped inside an internal array like tem, you should create a new tem array each time:

[list addObject:tem];
tem = [NSMutableArray arrayWithCapacity:1];
// new stuff added to tem will not appear in the array inside list

(Be careful with object ownership here -- this example uses a convenience method that will autorelease tem, but you may need to retain and release appropriately.)

If, on the other hand, you want the objects inside tem to be added into list, use addObjectsFromArray:

[list addObjectsFromArray:tem];
// objects in list will not be affected by subsequent changes to tem
[tem removeAllObjects];

Upvotes: 1

Related Questions