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

假设对象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 reference

self.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


慕仙森
浏览 524回答 3
3回答

ibeautiful

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