views:

121

answers:

2

Hello, I declare an NSArray in my code then building the array from another array. I process my NSArray and when I'm finished, I would like to release the objects, but I'm reusing this pointer to NSAarray again later to do the same process (creating the array from another array, process then releasing).. So I need to keep the pointer. What should I do ?

Here is roughly what I want to do, the buildArray is creating and returning an autoreleased NSArray :

NSArray *myArray;
for (int i = 0, i < 10, i++){
  [myArray arrayWithArray:[self buildArray]];
  // Here I process myArray
  [myArray = nil] // is my guess
  }

I need to keep a pointer to my NSArray, in order to reuse later in the loop, but what is happening to the objects created with [self buildArray]? What is the best to do in order not to keep unused object and arrays ?

Or maybe the best solution is simply to removeAllObject of the array..?

Thank you!

A: 

Don't do it like that. Instead, do:

for (int i = 0, i < 10, i++){
    NSArray *myArray = [self buildArray]; //buildArray should return an autoreleased object
    //Process array
    //myArray goes out of scope and is autoreleased later, releasing all of its objects
}
eman
+1  A: 

You can't reuse an NSArray since it's immutable. You can use an NSMutableArray (which supports -removeAllObjects) though.

If are you need is to keep the pointer, but doesn't need it constant within the loops, you could just use

loop {
  NSArray* myArray = [self buildArray];
  ...
  // myArray = nil; // optional.
}
KennyTM
so, when I'm setting myArray to nil, the objects will be released ?
Leo
@Leo: No it won't.
KennyTM
so what should i do in order to release them..? I thought it would asbuildArray is returning an autoreleased array..
Leo
@Leo: Nothing. An `-autorelease`'d object is automatically `-release`'d.
KennyTM