-1

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • 1
    Duplicates: [1](http://stackoverflow.com/questions/2032826/) [2](http://stackoverflow.com/questions/5140782/) [3](http://stackoverflow.com/questions/3169822/) [4](http://stackoverflow.com/questions/4700296/) [5](http://stackoverflow.com/questions/3394206/) [&c.](http://stackoverflow.com/search?page=2&tab=relevance&q=synthesize%20iphone) These all would've come up in "related questions" when you made your post. Please search before posting. – jscs May 03 '11 at 20:02

2 Answers2

0

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.

Paul Ardeleanu
  • 6,620
  • 2
  • 40
  • 41
0

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.

JeremyP
  • 84,577
  • 15
  • 123
  • 161
  • I guess, from now on, I should stick to method 1? And, is there any memory leaks on both methods? – detective-c May 03 '11 at 15:51
  • @detective-c: As coded you have no memory leaks in either fragment. Method 2 does have the potential for sending a message to a deallocated object though because you don't set the instance variable to nil after releasing it. – JeremyP May 03 '11 at 16:03
  • Thanks JeremyP, I will stick to method 1 then :) – detective-c May 03 '11 at 16:10