leochab
leochab

Reputation: 1112

NSArray : release its objects, but keep a pointer to it

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 = [NSArray 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!

Upvotes: 0

Views: 492

Answers (2)

kennytm
kennytm

Reputation: 523484

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.
}

Upvotes: 1

shosti
shosti

Reputation: 7422

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
}

Upvotes: 0

Related Questions