Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top