views:

57

answers:

2

I have done Objective-C way back when, and have recently (i.e. just now) read the documentation on Apple's site regarding the use of retain and release. However, there is a bit of code in their Creating an iPhone Application page that has me a bit confused:

- (void)setUpPlacardView
{
    // Create the placard view -- it calculates its own frame based on its image.
    PlacardView *aPlacardView = [[PlacardView alloc] init];
    self.placardView = aPlacardView;
    [aPlacardView release];  // What effect does this have on self.placardView?!
    placardView.center = self.center;
    [self addSubview:placardView];
}

Not seeing the entire class, it seems that self.placardView is also a PlacardView * and the assignment of it to aPlacardView doesn't seem to indicate it will retain a reference to it. So, it appears to me that the line I've commented ([aPlacardView release];) could result in aPlacardView having a retain count of 0 and thus being deallocated. Since self.placardView points to it, wouldn't that now point at deallocated memory and cause a problem?

+3  A: 

I have done Objective-C way back when,

Hi, Obj-C introduced an (evil) concept of properties in the meantime. Note that

 self.placardView=xxx;

and

 self->placardView=xxx;

is different. The former, by definition, calls [self setPlacardView:xxx] whereas the latter just assigns xxx into a member. Now, when you look at MoveMeView.h, you see the line

@property (nonatomic, retain) PlacardView *placardView;

and in MoveMeView.m

@synthesize placardView;

These tell the compiler to generate -setPlacardView: and placardView appropriately, using the standard retain/release semantics. For more details, see Apple's documentation for properties.

Yuji
The concept of properties is not evil, it's the dot notation that Apple introduced at the same time. It pollutes the syntax and causes endless confusion. Personally, I use properties a lot, but I use normal Objective-C syntax to get and set them.
JeremyP
Yes I agree with that. That's why I put parentheses around the word evil to start with. For me the dot notation is perfectly OK; I always remind myself that these are method calls. But I heartily agree that it is a great source of confusion for beginners.
Yuji
+1  A: 

Couple of things to point out;

if the property placardView is defined as being retained (@property (retain) ...) then self.placardView will call the setter generated by the compiler, which will include a retain.

Just incase this is new to you, properties and the associated @synthesize tell the compiler to generate - (void)setPlacardView:(UIView *)view and - (UIView *)placardView methods.

Another thing to note; addSubview: retains the view it's given. So without the release the view would have a retain count of 2. Releasing and then adding as a subview gives you a retain count of 1.

dannywartnaby