Reputation:
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
Where am I going in the wrong direction?
Upvotes: 2
Views: 860
Reputation: 8526
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.
Upvotes: 0
Reputation: 96927
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];
Upvotes: 1
Reputation: 7422
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.
Upvotes: 0