为了账号安全,请及时绑定邮箱和手机立即绑定

处理ARC中的指针对指针所有权问题

处理ARC中的指针对指针所有权问题

慕仙森 2019-11-25 10:55:41
假设对象A具有一个属性:@property (nonatomic, strong) Foo * bar;在实现中综合为:@synthesize bar = _bar;对象B操作a Foo **,如本例中从对象A进行的调用:Foo * temp = self.bar;[objB doSomething:&temp];self.bar = temp;是否可以合法地进行此操作?该doSomething:方法的正确声明是什么?此外,假设在我有机会设置属性之前,对象B可能已被释放bar(从而获得所指向的实例的所有权temp)-我将如何告诉ARC移交拥有的引用?换句话说,如果我希望以下示例代码起作用,我将如何处理ARC问题?Foo * temp = self.bar;    // Give it a reference to some current value[objB doSomething:&temp]; // Let it modify the referenceself.bar = nil;           // Basically release whatever we have_bar = temp;              // Since we're getting back an owning reference, bypass setter我在想什么呢编辑基于@KevinBallard的回答,我只想确认我的理解。它是否正确?对象A:@implementation ObjectA@synthesize bar = _bar;- (void)someMethod{    ObjectB * objB = [[ObjectB alloc] initWithFoo:&_bar];    // objB handed off somewhere and eventually it's "doSomething" method is called.}@end对象B:@implementation ObjectB{    Foo * __autoreleasing * _temp;}- (id)initWithFoo:(Foo * __autoreleasing *)temp{    id self = [super init];    if (self)    {        _temp = temp;    }    return self;}- (void)doSomething{    ...    *_temp = [[Foo alloc] init];     ...}@end这将产生一个编译时错误: passing address of non-local object to __autoreleasing parameter for write-back
查看完整描述

3 回答

?
ibeautiful

TA贡献1993条经验 获得超5个赞

您发现编辑错误。文档中将“输出”参数的处理方式称为“最不坏的解决方案”,因此有些混淆是可以理解的!同样__autoreleasing在一个参数上被证明是推断出的,因此@Kevin的答案是正确的,但从理论上讲是多余的...如果没有人击败我,我稍后会添加一个正确的答案。

查看完整回答
反对 回复 2019-11-25
  • 3 回答
  • 0 关注
  • 513 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信