ObjC:将间接指针转换为Objective-C指针 [英] ObjC: cast of an indirect pointer to an Objective-C pointer

查看:93
本文介绍了ObjC:将间接指针转换为Objective-C指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I change the following code to be compatible with 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]

推荐答案

自变量的类型应为(id *),即.指向对象而不是对象的指针.

The type of the argument should be (id *), ie. a pointer to an object, not an object.

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

But if you just want to return a value from a method that you need to execute on the main thread, a nicer solution is to use blocks and GCD:

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

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

This executes the method -popFilename on the main thread, and stores the result in poppedFilename. You must be careful not to call this method on the main thread, as it would deadlock. If you aren't sure if you are on the main thread, you could use something like this:

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

这篇关于ObjC:将间接指针转换为Objective-C指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆