Objective-C 中的 @property、@synthesize 和释放对象
我开发 iPad 游戏。我就遇到这个事情。这是我的示例代码:
方法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];
方法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];
方法1和2都有效,但这2种方法有什么区别(方法2的代码较少)?
我应该使用哪种方法?为什么?
和内存管理有关系吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
方法 2 从技术上讲是不正确的,因为通过向标题发送
-release
表示您不再对此感兴趣。您应该在之后立即将其设置为 nil,或者更好的是,将其设置为局部变量。方法 1 绝对没问题,其优点是,在
-dealloc
之外,如果您始终使用属性来引用它,则无需担心获取-retain
和-release
-right。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.不同之处在于,在方法 2 中,您无法从 Foo 对象外部访问标题。实例变量是类的私有变量。
另外,您需要确保平衡分配/保留和释放。
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.