0

(我们正在讨论自定义 UIViewController 子类中的代码——顺便说一下,我不使用 IB)好的,所以我在 - (void)loadView 中设置了 self.view 成员,然后我创建了我的控件和视图等等in - (void)viewDidLoad,然后将它们添加到子视图中。如果控件不是成员,如果我在方法中创建它并在本地释放它,我就是这样做的:(使用 UILabel)

- (void)viewDidLoad {
    UILabel *localLabel = [[UILabel alloc] initWithFrame:CGRectMake(81, 384, 148, 21)];
    localLabel.text = @"I'm a Label!";
    localLabel.AutoresizingMask = (UIViewAutoresizingFlexibleLeftMargin |
                                  UIViewAutoresizingFlexibleRightMargin |
                                  UIViewAutoresizingFlexibleBottomMargin);

    [self.view addSubview:localLabel];
    [localLabel release];
    [super viewDidLoad];
}

这只是我如何在本地创建标签、设置其属性、添加到子视图和发布的示例。但是对于一个成员,我这样做:

UILabel *lblMessage;
...
@property (nonatomic, retain)UILabel *lblMessage;
...
- (void)viewDidLoad {
    UILabel *localMessage = [[UILabel alloc] initWithFrame:CGRectMake(81, 384, 148, 21)];
    localMessage.text = @"I'm a Label!";
    localMessage.AutoresizingMask = (UIViewAutoresizingFlexibleLeftMargin |
                                      UIViewAutoresizingFlexibleRightMargin |
                                      UIViewAutoresizingFlexibleBottomMargin);
    self.lblMessage = localMessage;
    [localMessage release];

    [self.view addSubview:lblMessage];
    [super viewDidLoad];
}

但我也看到它完成了

...
- (void)viewDidLoad {
   UILabel *localMessage = [[UILabel alloc] initWithFrame:CGRectMake(81, 384, 148, 21)];
    localMessage.text = @"I'm a Label!";
    localMessage.AutoresizingMask = (UIViewAutoresizingFlexibleLeftMargin |
                                      UIViewAutoresizingFlexibleRightMargin |
                                      UIViewAutoresizingFlexibleBottomMargin);
    self.lblMessage = localMessage;

    [self.view addSubview:localMessage];
    [localMessage release];
    [super viewDidLoad];
}

就像我开始 iPhone 3 开发时那样:探索 sdk 书。注意添加局部变量,然后释放。我应该做什么?这有关系吗?

4

2 回答 2

1

如果lblMessage是保留属性(这通常是正确的),则没有功能差异。否则,release-before-addSubview 是一个错误,因为它会尝试添加一个已释放的对象作为子视图。

下面是对 的引用计数的快速演练localMessage,假设该属性lblMessage正在保留:

UILabel *localMessage = [[UILabel alloc]...  // retainCount is now 1
// Set up localMessage.  If you release'd now, you'd dealloc the object.
self.lblMessage = localMessage;  // retainCount is now 2
// You can safely call release now if you'd like.
[self.view addSubview:localMessage];  // retainCount is now 3.
[localMessage release];  // retainCount is now 2.

您希望retainCount以 2 结束,因为您实际上有 2 个对该对象的引用 - 您的成员指针lblMessage和 中的另一个保留指针self.view

于 2009-08-01T22:00:24.003 回答
0

作为成员的标签和本地范围标签是相互引用,所以它们是同一个对象,所以不管你用哪种方式,我只是没有本地并直接初始化标签

于 2009-08-01T21:57:38.767 回答