NSThread数据损坏

时间:2011-03-03 22:52:40

标签: objective-c ios nsthread

我有一个叫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)会使应用程序崩溃。我必须在从URL获取后使用我的dataArray中的数据,但不能。

我是Objective C的新手,所以如果我的错误很明显,我很抱歉:)

- UPDATE - 发送到此方法的对象未被保留,这就是问题所在!

1 个答案:

答案 0 :(得分:1)

如何创建和管理发送到后台线程的数组?

如果发生了崩溃,请发布回溯。


您的解决方法不是解决方法,只是缩小了杀死您应用的竞争条件的窗口。

最好的猜测(缺少显示数组如何创建的代码)是在后台线程完成数组和字符串之前,主线程正在释放你的数组。

为每个生成的线程保留一次数组,然后在完成后将其释放到线程中。

更好的是,使用GCD +块。

相关问题