user1280535
user1280535

Reputation: 347

NSMutableArray becomes empty?

I have noticed, that even that my code is working great, something strange happen.

Assume I have two arrays: passwordEntered and tempPasswordEntered.

After I get a new passwordEntered, I do this each time:

 tempPasswordEntered=[passwordEntered mutableCopy]; 

Then I clean :

 [passwordEntered  removeAllObjects];

then, next time I again do this (for the new passwordEntered):

 tempPasswordEntered=[passwordEntered mutableCopy]; 

So tempPasswordEntered has only the last passwordEntered, and not both of them. if first time it had 4 places in array,the second time it still has 4 places, so my question is, does the copy REPLACE the array ? its not added to the last place of it as when you addObject ?

Another thing: should I use retain instead?

Upvotes: 1

Views: 204

Answers (2)

prashant
prashant

Reputation: 1920

NSArray *retVal = [[NSArray alloc] initWithArray:fetchResults];
NSArray *retVal = [[NSArray alloc] initWithArray:[fetchResults copy]];
NSArray *retVal = [[NSArray alloc] initWithArray:[fetchResults retain]];

The latter two are simple leaks. The first is one way of making a copy, but retVal = [fetchResults copy]; is a better way to make a copy.

But, of course, you don't need a copy at all. That isn't the problem. You go on to say that the only thing that doesn't crash is an empty result set.

That indicates one of two things; either your result set is corrupt (unlikely) or you are accessing the result set incorrectly (likely).

Upvotes: 0

Carl Veazey
Carl Veazey

Reputation: 18363

The line tempPasswordEntered=[passwordEntered mutableCopy]; is a variable assignment, and like other assignments it changes the value of the variable completely. In this case, tempPasswordEntered now points to a copy of passwordEntered, which has only a single object in it. So yes, it does replace the array, like any other assignment would.

If you wanted to add the objects in passwordEntered to tempPasswordEntered, try [tempPasswordEntered addObjectsFromArray:passwordEntered].

It sounds like what you want is mutableCopy, not retain, but I don't really know what your requirements are exactly so I can't say much more. You should probably be using ARC anyways :)

Upvotes: 1

Related Questions