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