ObjC:对Objective-C指针的间接指针的强制转换

时间:2011-12-13 14:50:13

标签: objective-c automatic-ref-counting

如何更改以下代码以与ARC兼容:

MyObj* fn = nil;
[self performSelectorOnMainThread:@selector(popSomething:) withObject:(id)&fn waitUntilDone:YES];

现在,我收到以下错误:

error: cast of an indirect pointer to an Objective-C pointer to '__strong id' is disallowed with ARC [4]

2 个答案:

答案 0 :(得分:2)

如果您希望主线程更新字符串,那么更好的方法是使用可变字符串并将其传递给主线程:

NSMutableString* fn = [NSMutableString string];
[self performSelectorOnMainThread:@selector(queuedFileNamesPop:) withObject:fn waitUntilDone:YES];

然后主线程可以简单地更新字符串。

答案 1 :(得分:0)

参数的类型应为(id *),即。指向对象的指针,而不是对象。

但是,如果您只想从需要在主线程上执行的方法返回一个值,那么更好的解决方案是使用块和GCD:

__block id poppedFilename;
dispatch_sync(dispatch_get_main_queue(), ^{
     poppedFilename = [self popFilename];
});
// do something with the popped file

这将在主线程上执行方法-popFilename,并将结果存储在poppedFilename中。你必须小心不要在主线程上调用这个方法,因为它会死锁。如果您不确定自己是否在主线程上,可以使用以下内容:

__block id poppedFilename;
if ([NSThread isMainThread]) {
     poppedFilename = [self popFilename];
} else {
     dispatch_sync(dispatch_get_main_queue(), ^{
         poppedFilename = [self popFilename];
     });
}
相关问题