可可与ARC:设置强大的属性

时间:2014-09-24 19:00:09

标签: automatic-ref-counting

简单问题:

我有一个名为player的AVPlayer属性(可能是任何强大的属性,例如它只是AVPlayer)。

如果已经已分配(并且不是nil),我重新分配它而不将其设置为nil:

self.player = [[AVDelegatingPlayer alloc] initWithURL:[NSURL URLWithString:urlString]];

ARC环境中存在内存影响吗?

1 个答案:

答案 0 :(得分:1)

查看用于将对象存储到__strong变量的clang源代码。

https://github.com/llvm-mirror/clang/blob/master/lib/CodeGen/CGObjC.cpp#L2108-L2119

// Retain the new value.
newValue = EmitARCRetain(type, newValue);

// Read the old value.
llvm::Value *oldValue = EmitLoadOfScalar(dst, SourceLocation());

// Store.  We do this before the release so that any deallocs won't
// see the old value.
EmitStoreOfScalar(newValue, dst);

// Finally, release the old value.
EmitARCRelease(oldValue, dst.isARCPreciseLifetime());

所以你的代码将编译如下。

id newValue = [[AVDelegatingPlayer alloc] initWithURL:[NSURL URLWithString:urlString]];
id oldValue = self.player;
self.player = newValue;
[oldValue release];