【发布时间】:2010-11-14 11:55:33
【问题描述】:
我在多线程 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),当我释放线程的NSAutoreleasePool 时,我的程序会因EXC_BAD_ACCESS 而崩溃。
我错过了什么?
仅供参考,这是线程的主要代码:
- (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
}
感谢您的帮助!
【问题讨论】:
标签: iphone objective-c memory-management autorelease retain