itai alter
itai alter

Reputation: 601

NSMutableArray not retaining?

I'm having some issues with my Arrays, I hoped anyone here can tell me what I'm doing wrong.

I have 3 arrays: tmpAnswersArray, localAnswersArray & finalAnswersArray. I also have a method to shuffle a given array in the same class.

The first NSLog shows the count for the localAnswersArray is 6 (how it supposed to be).

The third NSLog shows the localAnswersArray count is 0, even though I didn't change anything in that array.

localAnswersArray = [[NSMutableArray alloc] init];
  localAnswersArray = [self shuffleArray:tmpAnswersArray];

  [tmpAnswersArray release];

  NSLog(@"Shuffled localAnswersArray (count = %d) & removed tmpAnswersArray",[localAnswersArray count]);

  finalAnswersArray = [[NSMutableArray alloc] init];
  NSLog(@"init finalAnswersArray");


  for (int arrayCount = 0; arrayCount < 6; arrayCount++) {
   NSLog(@"TEST ---> %d",[localAnswersArray count]);
   [finalAnswersArray addObject:[localAnswersArray objectAtIndex:arrayCount]];
  }

Is the first line of this code also retains the array?

Do I have to retain it manually somehow?

Why is the array count drops to 0 all of a sudden?

Thanks for any help!

Upvotes: 0

Views: 987

Answers (1)

Dave DeLong
Dave DeLong

Reputation: 243146

You need to review the Memory Management Guidelines.

localAnswersArray = [[NSMutableArray alloc] init];
localAnswersArray = [self shuffleArray:tmpAnswersArray];

You create an array (that you own), then immediately replace it with a different array.

And it would seem that your entire block of code could be replaced with this:

finalAnswersArray = [[self shuffleArray:tmpAnswersArray] mutableCopy];

Upvotes: 1

Related Questions