I am trying to implement the NSFastEnumeration protocol for a sqlite query.
I am running into: message sent to deallocated instance
- (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id __unsafe_unretained *)stackbuf count:(NSUInteger)len {
// First call
if(state->state == 0) {
state->mutationsPtr = &state->extra[0];
state->state = 1;
sqlite3_reset(self.statement);
}
state->itemsPtr = stackbuf;
NSUInteger count = 0;
while (count < len) {
int result = sqlite3_step(self.statement);
if (result == SQLITE_DONE) {
break;
}
MyRow *row = [self queryRow];
stackbuf[count] = row;
count += 1;
}
return count;
}
-(MyRow *) queryRow {
MyRow * row = // query sqlite for row
return row;
}
It seems as if the 'row' object is not being retained, so when it needs to be accessed in loop its already been deallocated.
Do I need to save the results when iterating in 'countByEnumeratingWithState' in a'strong' dataset, so that it is retained?
IE:
@property (nonatomic, strong) NSMutableArray *resultList;
Then inside the while loop:
while (count < len) {
int result = sqlite3_step(self.statement);
if (result == SQLITE_DONE) {
break;
}
MyRow *row = [self queryRow];
[self.resultList addObject:row]; // throw into a strong array so its retained
stackbuf[count] = row;
count += 1;
}
EDIT:
A little more research reveals that maybe I can just use __autoreleasing:
MyRow * __autoreleasing row = [self queryRow];
Without having to maintain a strong array of objects. Is this the right solution?