gpt4 book ai didi

iphone - Objective-C : why release immediately after creating ui object

转载 作者:太空狗 更新时间:2023-10-30 03:46:12 24 4
gpt4 key购买 nike

许多 iPhone 代码示例(来自 Apple 等)包含如下代码:

- (void)viewDidLoad {
CGRect applicationFrame = [[UIScreen mainScreen] applicationFrame];

// add the top-most parent view
UIView *contentView = [[UIView alloc] initWithFrame:applicationFrame];
contentView.backgroundColor = [UIColor blackColor];
self.view = contentView;
[contentView release];

levelView = [[LevelView alloc] initWithFrame:applicationFrame viewController:self];
[self.view addSubview:levelView];

calibrationView = [[CalibrationView alloc] initWithFrame:applicationFrame viewController:self];
}

此代码段来自 BubbleLevel 示例项目。

我的问题:为什么要向 contentView 发送发布消息?我们在 self.view 中保留了对 contentView 的引用,我们显然希望在应用程序的生命周期内使用它,而不仅仅是在这个方法中。调用 release 不会导致 View 被释放吗?

最佳答案

Ölbaum 说得对,self.view = contentView; 将保留您的 View ,这意味着它不会被释放。然而,这种行为并不总是这样:

如果您查看 UIViewController 的文档(或标题),您会看到 view 属性声明如下:

@property(nonatomic, retain) UIView *view;

这意味着无论何时设置 View 属性(foo.view = anotherView[foo setView:anotherView];),另一个 View 将被保留。如果 view 属性声明为:

@property(nonatomic, assign) UIView *view;

那么 View 将保留。它会对实例变量做一个简单的指针赋值。在这种情况下,您认为 contentView 的后续 release 会破坏 View 是正确的,这意味着 Controller 将有一个过时的指针,这意味着您的应用程序可能会崩溃.

换句话说,当您使用属性时,请确保您知道它们是retain 还是assign。 (如果没有说明,则为 assign)。然后相应地处理您的内存管理。

关于iphone - Objective-C : why release immediately after creating ui object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1386553/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com