xcode 什么时候用 Objective-C 在 iPhone 编程中分配和初始化对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2174224/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 19:05:57  来源:igfitidea点击:

When do I alloc and init objects in iPhone programming with Objective-C?

iphonexcodesdkuilabel

提问by Anthony Glyadchenko

Sometimes when I program for the iPhone, I wonder when you have to allocate and initialize objects and when not to. When you are using UI controls, it seems as if you don't have to do so. Is this true and why?

有时当我为 iPhone 编程时,我想知道什么时候必须分配和初始化对象,什么时候不需要。当您使用 UI 控件时,您似乎不必这样做。这是真的吗?为什么?

(Assume that they have been declared in the .h of the view controller.)

(假设它们已在视图控制器的 .h 中声明。)

Example:

例子:

label1.text = @"Hello";

vs

对比

label1 = [[UILabel alloc] init];
label1.text = @"Hello";

Is this because I'm using Interface Builder? Would I have to do this if I were to write our my GUI in code?

这是因为我在使用 Interface Builder 吗?如果我要在代码中编写我们的 GUI,我是否必须这样做?

回答by Ana Betts

Your confusion is because of the NIB file - a NIB file is basically a frozen object graph (i.e. a object with children, who has other children, etc). When you load that NIB file, the runtime calls all of the allocs and inits foryou, so that they're already created.

你的困惑是因为 NIB 文件 - NIB 文件基本上是一个冻结的对象图(即有孩子的对象,还有其他孩子等)。当您加载该 NIB 文件时,运行时会您调用所有分配和初始化,以便它们已经创建。

When you want to create an object that hasn't been previously specified in the NIB file, that's when you need alloc/init.

当您想创建一个先前未在 NIB 文件中指定的对象时,您就需要使用 alloc/init。

回答by Ben Gottlieb

You basically need to alloc/init ALL objects except for static strings, as above. Even when you're using convenience methods, such as +[NSString stringWithFormat:...], behind the scenes an alloc and init is still occurring. These convenience methods usually just do the alloc and init, and then toss in an -autorelease as well so that you don't have to worry about cleaning up.

您基本上需要分配/初始化除静态字符串之外的所有对象,如上所述。即使您使用方便的方法,例如 +[NSString stringWithFormat:...],在幕后仍然会发生 alloc 和 init。这些方便的方法通常只执行 alloc 和 init,然后还加入 -autorelease,这样您就不必担心清理了。

If you're just creating a temporary object, and there's a convenience method that fits, use it. If you want your object to stay around and there's convenience method, usually it's fine to call it and add a -retain, or just use alloc/init.

如果您只是创建一个临时对象,并且有适合的便捷方法,请使用它。如果你想让你的对象留在周围并且有方便的方法,通常可以调用它并添加一个-retain,或者只使用alloc/init。

Obviously, if there's no convenience method, use alloc/init.

显然,如果没有方便的方法,请使用 alloc/init。