Anthony Glyadchenko
Anthony Glyadchenko

Reputation: 3622

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

Upvotes: 1

Views: 5092

Answers (2)

Ana Betts
Ana Betts

Reputation: 74654

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.

Upvotes: 5

Ben Gottlieb
Ben Gottlieb

Reputation: 85522

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.

Upvotes: 2

Related Questions