tags:

views:

23

answers:

1

Hi,

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é

+1  A: 

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.

Carl Norum
Thanks. So I'll stick with the auto release version (which version is better coding style?).Remaining problem is: when I'm done with my "capSession", I call [self.capSession stopRunning];self.capSession = nil;But as soon as I put the "nil" line in, the app crashes. What's the problem? A new session is created every time (see code above).
Krumelur
Would it also be correct to: self.capSession = [[AVCaptureSession alloc] init]; [self.capSession release];?
Krumelur