Objective-C:为什么这个属性赋值没有按预期工作?

时间:2010-08-20 22:35:04

标签: objective-c

当谈到Objective-C的细节时,我有时会感到困惑。

拥有此头文件: .H:

   AVCaptureSession *capSession;
   @property(nonatomic, retain) AVCaptureSession *capSession;

为什么在ObjC中这样做是正确的:

.m:

// Create instance locally, then assign to property and release local instance.
AVCaptureSession *session = [[AVCaptureSession alloc] init];
self.capSession = session;
[session release];

为什么它不正确/不工作/导致不正确的行为:

的.m:

// Directly assign to property.
    self.capSession = [[AVCaptureSession alloc] init];

我看到的主要问题是我在第二版中缺少“发布”。可以使用“autorelease”作为替代方案:

  self.capSession = [[[AVCaptureSession alloc] init] autorelease];

1 个答案:

答案 0 :(得分:1)

是的,您的autorelease替代方案没问题。 alloc / init创建对象的方式为您提供了一个保留对象。然后,您通过self.capSession = session使用您的访问者,再次调用retain,因此您需要release它。 autorelease最终会变成一样。

相关问题