如何使变量的地址成为 NSObject
中的强属性?我有一个名为 SCPFMessageThreadQuery
的类,它是通过传递 SCPFMessageThread
变量的地址来分配初始化的。
@interface SCPFMessageThreadQuery ()
// This declaration seems correct.
@property (nonatomic) SCPFMessageThread *__strong *thread;
- (id)initWithRootMessage:(SCPFMessage *)root threadAddress:(SCPFMessageThread **)address;
@end
@implementation SCPFMessageThreadQuery
// Xcode somehow makes the ownership type __autoreleasing here during autocompletion.
- (id)initWithRootMessage:(SCPFMessage *)root threadAddress:(SCPFMessageThread *__autoreleasing *)address
{
if (self = [super init]) {
_root = root;
// ERROR HERE. Xcode complains about changing the ownership of address.
_thread = address;
}
return self;
}
@end
我得到的错误是这样的:
Assigning 'SCPFMessageThread *__autoreleasing *' to 'SCPFMessageThread *__strong *' changes retain/release properties of pointer
我计划在我的 View Controller 中以下列方式使用此类:
SCPFMessageThread *thread = self.thread; // self.thread can be nil
SCPFMessageThreadQuery *query = [[SCPFMessageThreadQuery alloc]
initWithRootMessage:self.rootMessage threadAddress:&thread];
我真的需要在这里传递地址。我将对我们的 API 进行多次调用,以完成应用程序代码中单个对象 (SCPFMessageThread
) 的信息。请不要问我为什么 API 不自己执行 JOIN。
最佳答案
除局部变量外,您不能对任何内容使用__autoreleasing
存储。自动释放是每线程行为。跨线程或跨栈帧共享 __autoreleasing
存储空间是不安全的,这可能会弹出自动释放池。
SomeObject **
类型的参数默认为__autoreleasing
。您可以更改您的方法声明,使其适用于强变量。然后你可以直接将它与你的 strong 属性的 ivar 一起使用:
- (id)initWithRootMessage:(SCPFMessage *)root threadAddress:(SCPFMessageThread * __strong *)address
请注意,当您获取 ivar 或局部变量的地址时,ARC 不会确保包含的对象或堆栈框架在您需要的时间内一直存在。
关于ios - 如何将 __autoreleasing 地址保留为类中的强属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21848060/