ios - 如何将 __autoreleasing 地址保留为类中的强属性?

标签 ios iphone objective-c c pointers

如何使变量的地址成为 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/

相关文章:

objective-c - MPMoviePlayerController 错误或功能 : Setting initialPlaybackTime to t seconds hides the time-slider upto t

ios - 如何在 Mapbox 中添加一张大图像作为叠加层?

iphone - UIDatePickerModeCountDownTimer 模式下的 UIDatePicker : how to change to minutes and seconds mode?

iphone - 如何将 PDF 文档(来自文档目录)附加到电子邮件

ios - 谷歌分析实时不工作

iphone - 如何使用 UIsearchBar 委托(delegate)方法关闭键盘?我尝试了所有方法,但没有用。

ios - UIImagePickerController 中的左右 barButtons 字体

iphone - 每天下午 5 点重复 UILocalNotification

iphone - 如何用不同的 UITextField 覆盖 UITextField

ios - 根据键的值从 NSDictionary 的 NSMutableArray 中删除重复项