-1

我正在开发 iPad 游戏。我遇到这件事。这是我的示例代码:

方法一:

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];

方法二:

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];

方法 1 和 2 都有效,但是这两种方法有什么区别(方法 2 的代码更少)?

我应该使用哪种方法,为什么?

它与内存管理有关吗?

4

2 回答 2

0

不同之处在于,在方法 2 中,您将无法从 Foo 对象外部访问标题。实例变量是类私有的。

此外,您需要确保平衡分配/保留和释放。

于 2011-05-03T11:36:26.240 回答
0

方法 2 在技术上是不正确的,因为通过发送-release到标题表明您不再对它感兴趣。您应该立即将其设为 nil,或者更好的是,将其设为局部变量。

方法 1 绝对没问题,它的优点是,-dealloc只要您始终使用属性来引用它,您就不必担心获取-retain和 -正确-release

于 2011-05-03T13:40:32.930 回答