我有一个Thread调用了10次:
[NSThread detachNewThreadSelector:@selector(workInBackground:) toTarget:self withObject:sendArray];这是"workInBackground“方法:
- (void)workInBackground:(NSArray*)dataArray{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; // create release pool
// display dataArray sent from Main Thread
NSLog(@"%i, %@", [[dataArray objectAtIndex:0] intValue], [dataArray objectAtIndex:1]);
// Fetch data from URL
NSString *myURL = [NSString stringWithFormat:@"http://somesite.com/index.php?s=%@", [dataArray objectAtIndex:1]];
NSURL *url = [[NSURL alloc] initWithString:myURL];
NSString *strResult = [[NSString alloc] initWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
// display dataArray sent from Main Thread ... AGAIN
NSLog(@"this will show");
NSLog(@"%i, %@", [[dataArray objectAtIndex:0] intValue], [dataArray objectAtIndex:1]);
NSLog(@"this will not show");
// Code that returns super cool data to the main thread
[pool release]; // empty pool我不能100%确定数据确实会损坏,但我不明白为什么同一行代码(NSLog)会使应用程序崩溃。在Fetch from URL之后,我必须使用我的dataArray中的数据,但是不能。
我刚接触Objective C,所以如果我的错误很明显,我很抱歉:)
-- UPDATE --发送到此方法的对象没有保留,这就是问题所在!
发布于 2011-03-04 06:57:33
如何创建和管理发送到后台线程的数组?
如果你有一个崩溃,发布回溯。
你的变通方法不是修复,它只是缩小了任何竞争条件正在杀死你的应用程序的窗口。
最好的猜测(缺少显示数组是如何创建的代码)是在后台线程处理完数组和字符串之前,主线程正在释放数组。
为每个派生的线程保留一次数组,然后在使用完数组后在线程中释放它。
更好的是,使用GCD +块。
https://stackoverflow.com/questions/5187625
复制相似问题