views:

112

answers:

3

I am trying to get the following loop working to fill 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 try to shape this loop it falls over the release of itemsArray

  • when I use release (as above), the array does not re-initialise as a new instance with alloc. Whilst expecting emptyness, the next Object is added to the old array.
  • when I use removeAllObjects, my Array is emptied and so is the array attached to myArray.

Where am I going in the wrong direction?

+1  A: 

You might place:

itemsArray = nil;

after the release message, to ensure that you're not pointing to an old instance.

EDIT

Looking at this again, you have:

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

This is scoped within the if statement.

So take out NSMutableArray and just use:

itemsArray = [[NSMutableArray alloc] init];
Alex Reynolds
Hi Alex, tried it, but leads to an "[NSCFArray count]: method sent to an uninitialized mutable array object'" error ...
iFloh
that's it, thank you very much
iFloh
+1  A: 

Don't write NSMutableArray *itemsArray = [[NSMutableArray alloc] init];--you're re-declaring the variable in the scope of the if statement, so outside the if statement, itemsArray will still refer to the old value (I'm not sure why the compiler isn't complaining). You can just say itemsArray = [[NSMutableArray alloc] init] instead.

You also might want to use autorelease, to simplify, as well.

eman
thanks a lot, that's it
iFloh
+1  A: 

The others have found the problem, but have created a new problem. The first time you create the 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 occur as many times as desired.

EDIT: You could write NSMutableArray *itemsArray; before the if statement, and then use itemsArray = [[NSMutableArray alloc] init]; in the if statement.

jrtc27
Hi jrtc27, this is how I have it now, just not visible in the above code sample, thanks a lot
iFloh