首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >NSThread数据损坏

NSThread数据损坏
EN

Stack Overflow用户
提问于 2011-03-04 06:52:40
回答 1查看 245关注 0票数 0

我有一个Thread调用了10次:

代码语言:javascript
复制
[NSThread detachNewThreadSelector:@selector(workInBackground:) toTarget:self withObject:sendArray];

这是"workInBackground“方法:

代码语言:javascript
复制
- (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 --发送到此方法的对象没有保留,这就是问题所在!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-03-04 06:57:33

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

如果你有一个崩溃,发布回溯。

你的变通方法不是修复,它只是缩小了任何竞争条件正在杀死你的应用程序的窗口。

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

为每个派生的线程保留一次数组,然后在使用完数组后在线程中释放它。

更好的是,使用GCD +块。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5187625

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档