开发者

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

Sometimes when I program for the iPhone, I wonder when you have to开发者_StackOverflow社区 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?

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

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?


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 for you, so that they're already created.

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


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.

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.

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜