Krumelur
Krumelur

Reputation: 33068

Objective-C: why is this property assignment not working as expected?

I'm still sometimes puzzled when it comes to details of Objective-C.

Having this header file: .h:

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

Why is it correct in ObjC to do this:

.m:

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

and why is it incorrect/not working/resulting in incorrect behavior to do that:

.m:

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

The main problem I see is that I'm missing a "release" in the 2nd version. Would it be okay to use "autorelease" as an alternative:

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

René

Upvotes: 1

Views: 262

Answers (1)

Carl Norum
Carl Norum

Reputation: 225202

Yes, your autorelease alternative is fine. The alloc/init way of creating objects gives you a retained object. Then you use your accessor via self.capSession = session, which calls retain again, so you need to release it. autorelease will end up being the same.

Upvotes: 1

Related Questions