-1

I have a loop where I'd like to redefine the contents of an array with every iteration. I'm worried about leaks. Is there anything wrong with this code?

for (int i=0;i<numberOfReps;i++){
  NSArray *shuffledArray=[self shuffleArray:originalArray];
  // use shuffled array
}

Thanks for reading!

EDIT:

Here is shuffleArray (credit to Kristopher Johnson from What's the Best Way to Shuffle an NSMutableArray?):

-(NSArray*)shuffleArray:(NSArray*)array{
    NSMutableArray *newArray=[NSMutableArray arrayWithArray:array];
    NSUInteger count = [newArray count];
    for (NSUInteger i = 0; i < count; ++i) {
        // Select a random element between i and end of array to swap with.
        int nElements = count - i;
        int n = (arc4random() % nElements) + i;
        [newArray exchangeObjectAtIndex:i withObjectAtIndex:n];
    }
    return [NSArray arrayWithArray:newArray];
}

(And I am using ARC.)

Community
  • 1
  • 1
Rogare
  • 3,234
  • 3
  • 27
  • 50
  • You need to post the contents of the -shuffleArray method. There's no leak in the code that you have posted thus far. – max_ Feb 16 '14 at 17:05
  • You can easily test this by creating your own class and putting an NSLog statement in the `init` and `dealloc` methods. – nhgrif Feb 16 '14 at 17:13

2 Answers2

1

Assuming we're using ARC and the shuffleArray method is fine, this bit of code will be fine too. There's no leak in the code you've posted.

Each shuffledArray is deallocated at the end of each iteration of the loop (unless you're saving it somewhere else). And there is only one originalArray.


EDIT: After the edit, again, assuming we're using ARC, there's no leak with the code. newArray is released as soon as shuffleArray returns. shuffledArray is released at the end of the loop iteration. originalArray has reference outside the for loop, and remains in memory until it has no more references.

The only possible leak here would be whatever you do with shuffledArray in the //use shuffled array section of the loop.

nhgrif
  • 61,578
  • 25
  • 134
  • 173
1

That depends.

Only if you're sure that the method shuffleArray returns an autoreleased object then there's no harm with your code, (and this assuming you're not using ARC).

EDIT: After seeing your code update, regardless if you're using ARC, there's no leak

Merlevede
  • 8,140
  • 1
  • 24
  • 39