I am trying to understand why my application crashes and I am going through my code. I am pretty sure that this is a valid use of autorelease:
(part of the code)
- (NSArray *)allQuestionsFromCategories:(NSArray *)categories {
...
NSMutableArray *ids = [[[NSMutableArray alloc] init] autorelease];
while (sqlite3_step(statement) == SQLITE_ROW) {
[ids addObject:[NSNumber numberWithInt:sqlite3_column_int(statement, 0)]];
}
return [NSArray arrayWithArray:ids];
}
Is this valid? The NSArray arrayWithArray returns an autorelease object doesn’t it? I also have some difficulties in understanding the scope of autoreleased objects. Would the autoreleased object (if it is in this case) be retained by the pool through out the method that invoked the method that this code is a part of?
- (void)codeThatInvokesTheCodeAbove {
NSArray *array = [self.dao allQuestionsFromCategories];
...
}
Would the array returned be valid in the whole codeThatInvokesTheCodeAbove method without retaining it? And if it was, would it be valid even longer?
Got some issues understanding the scope of it, and when I should retain an autorelease object.
[NSArray arrayWithArray:]returns an autoreleased object. If you wantcodeThatInvokesTheCodeAboveto take ownership of the array, you should callretainon it (and renamecodeThatInvokesTheCodeAboveaccording to apple’s guidelines). Otherwise, if you don’t care that ownership of the object is ambiguous then your code is okay.In other words,
[NSArray arrayWithArray:]returns an array that you don’t own, but you have access to it for at least this run cycle. Therefore,codeThatInvokesTheCodeAbovewill have access to it for at least this run cycle. Ownership is not clear, since nobody calledalloc,copy,new, ormutableCopyorretain. It is implied thatNSArraycalled autorelease before returning the new array, thus relinquishing ownership.My information comes from http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmRules.html%23//apple_ref/doc/uid/20000994-BAJHFBGH.
So, to answer your question, yes your posted code is valid. Whether it’s correct depends on what it is you are trying to accomplish.