我在多线程 iPhone 应用程序中有一个与内存管理相关的问题。假设我们有这个方法,它在与主 UI 线程不同的线程中调用:
- (BOOL)fetchAtIndex:(NSUInteger)index
{
NSURL *theURL = [NSURL URLWithString:[queryURLs objectAtIndex:index]];
// Pay attention to this line:
NSData *theData = [[NetworkHelper fetchFromNetwork:theURL] retain];
// Some code here...
// Now what should I do before returning result?
//[theData release]; ??
//[theData autorelease]; ??
return YES;
}
如您所见,我保留NSData
了从网络操作中返回的信息。问题是:为什么我不应该在我的方法结束时释放(或自动释放)它?我让它工作的唯一方法是首先使用retain
,然后什么都不用。如果我使用任何其他组合(什么都没有;retain
然后release
或autorelease
),EXC_BAD_ACCESS
当我释放线程的NSAutoreleasePool
. 我错过了什么?
仅供参考,这是线程的主要代码:
- (void)threadedDataFetching;
{
// Create an autorelease pool for this thread
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
// Reload data in separate thread
[self fetchAtIndex:0];
// Signal the main thread that fetching is finished
[self performSelectorOnMainThread:@selector(finishedFetchingAll) withObject:nil waitUntilDone:NO];
// Release all objects in the autorelease pool
[pool release]; // This line causes EXC_BAD_ACCESS
}
谢谢你的帮助!