开发者

Basic question on retain/release semantics from Apple's reference library

开发者 https://www.devze.com 2022-12-26 04:42 出处:网络
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开发者_StackOverflow社区.However, there is a bit

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开发者_StackOverflow社区. 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?


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号