开发者

@property, @synthesize and releasing objects in Objective-C

开发者 https://www.devze.com 2023-03-02 17:30 出处:网络
I developing iPad games. I encounter this thing. This is my sample code: Method 1: Foo.h @interface Foo : UIView{

I developing iPad games. I encounter this thing. This is my sample code:

Method 1:

Foo.h

@interface Foo : UIView{
    UILabel *title;
    .... // Other objects like UISlider, UIbuttons, etc.
}

// I add @property for all the objects.
@property (nonatomic, retain) UILabel *title;

... blablabla

Foo.m
// I synthesize all the properties.
@synthesize title;
... blablabla

// Release in dealloc method
[title release];
....
[super dealloc];

Method 2:

Foo.h

@interface Foo : UIView{
    UILabel *title;
    .... // Others object like UISlider, UIbuttons, etc.
}
// But this time I didn't add @property, synthesize and release.

Foo.m
// When I need the label, I allocate it:
title = [[UILabel alloc] initWithRect: CGRect(10, 10, 100, 30)];
title.text = @"test";
[self addSubview: title];
[title release];

Both method 1 and 2 work, but what's the difference between the 2 methods (method2 has less code)?

Which method should I use开发者_如何学编程 and why?

Has it something to do with memory management?


Method 2 is technically incorrect since by sending -release to title you indicate that you are no longer interested in it. You should make it nil straight after, or better yet, make it a local variable.

Method 1 is absolutely fine and has the advantage that, outside of -dealloc provided you always use the property to refer to it, you do not need to worry about getting -retain and -release -right.


The difference is that, in Method 2, you won't have access to the title from outside the Foo object. Instance variable are private to the class.

Also, with you need to make sure you balance the alloc/retain and releases.

0

精彩评论

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