Building an array of arrays
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 u开发者_Go百科se 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?
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];
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.
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.
精彩评论