Creating an array of arrays

I am trying to get the following loop to populate an array of arrays:

while (condition) {
[itemsArray fillFromDB];

if (! [checkArray containsObject:checkFlag]) {
  // Add existing itemsArray to myArray
  if (itemsArray.count) {
    // add the itemsArray to myArray and create a new instance of itemsArray
    [myArray addObject:itemsArray];
    [itemsArray release];
    NSMutableArray *itemsArray = [[NSMutableArray alloc] init];
  }
  [itemsArray addObject:myObject];
  [checkArray addObject:checkFlag];
} else {
  [itemsArray addObject:tmpEvent];
}  }

      

However I am trying to form this loop that falls on the release of itemsArray

  • when i use release (as above) the array is not reinitialized as a new instance with alloc. Waiting for emptiness, the next object is added to the old array.
  • when i use removeAllObjects my array is empty and so the array is bound to myArray.

Where am I going in the wrong direction?

+2


a source to share


3 answers


You can place:

itemsArray = nil;

      

after the post release

to make sure you are not pointing to an old copy.

EDIT

Looking at this again, you have:



NSMutableArray *itemsArray = [[NSMutableArray alloc] init];

      

This is the area inside the operator if

.

So pull out NSMutableArray

and just use:

itemsArray = [[NSMutableArray alloc] init];

      

+2


a source


Don't write NSMutableArray *itemsArray = [[NSMutableArray alloc] init];

- you're re-declaring the variable in the scope of the statement if

, so outside of the statement if

itemsArray

it will still refer to the old value (I "Don't know why the compiler isn't complaining.) You can just say itemsArray = [[NSMutableArray alloc] init]

.



You might also want to use autorelease to keep things simple.

+1


a source


Others found a problem, but created a new problem. The first time you create a mutable array, you need to use NSMutableArray *itemsArray = [[NSMutableArray alloc] init];

. Then, after, you can release

and use itemsArray = [[NSMutableArray alloc] init];

. It is important that the first one (the one that creates the pointer) occurs only once, and the rest can happen as many times as needed.

EDIT: You can write NSMutableArray *itemsArray;

before the statement if

and then use itemsArray = [[NSMutableArray alloc] init];

in the statement if

.

+1


a source







All Articles