views:

76

answers:

2

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?

(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?

+1  A: 

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.

Ben Gottlieb
One thing to note is that when he is using interface builder, the objects are allocated for him from the nib file and he doesn't have to do that manually.
chpwn
ah, that's a good and important distinction.
Ben Gottlieb
+3  A: 

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.

Paul Betts