【问题标题】:@property, @synthesize and releasing objects in Objective-C在 Objective-C 中 @property、@synthesize 和释放对象
【发布时间】:2011-05-03 11:32:15
【问题描述】:

我正在开发 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];

方法一和方法二都可以,但是这两种方法有什么区别(方法二的代码少)?

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

这和内存管理有关吗?

【问题讨论】:

  • 重复:12345&c.这些都会在您发帖时出现在“相关问题”中。发帖前请先搜索。

标签: objective-c memory-management synthesizer


【解决方案1】:

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

方法 1 绝对没问题,它的优点是,在 -dealloc 之外,只要你总是使用属性来引用它,你就不必担心得到 -retain-release -right。

【讨论】:

  • 我想,从现在开始,我应该坚持方法一吧?而且,这两种方法都存在内存泄漏吗?
  • @detective-c:按照编码,您在任何一个片段中都没有内存泄漏。方法 2 确实有可能向已释放的对象发送消息,因为您在释放实例变量后没有将其设置为 nil。
  • 谢谢 JeremyP,我会坚持方法 1 :)
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-22
    • 2011-01-26
    • 1970-01-01
    • 1970-01-01
    • 2011-11-21
    相关资源
    最近更新 更多