1

Generally speaking, when should you make a variable in Objective C an instance variable?

For instance, say I got an UIViewController with an UILabel. In what cases would I have the UILabel as an instance variable vs doing something like this:

UILabel *label = [[UILabel alloc] init];
//set text of label
[view.addSubview label];
[label release];

3 Answers 3

2

If you need a moderately persistent handle on any resource, you should make it an instance variable, if the resource in question should remain at least moderately persistent.

In the example above, then yes; the label should be an instance variable, probably one assigned using an IBOutlet.

Generally speaking, most things that live in UIKit (as opposed to Foundation) benefit from being instantiated through NIB files and subsequently accessed through outlets.

This isn't solely a performance issue; it also has to do with memory management and fragmentation, as well as simplifying, in most cases, translation and internationalization.

Sign up to request clarification or add additional context in comments.

Comments

2

To your specific case, if you are going to need to access that label at a later point in time (say to change the text) keeping an ivar will save you some effort trying to find it again.

General reasons would be for persistence, scope, and convenience.

Comments

0

In your particular example, the object is written as a variable so that it can be sent a release message after adding it to a view (which retains it).

The equivalent code without a variable is:

[view addSubview:[[[UILabel alloc] init] autorelease]];

We don't need to send a release, because we're autoreleasing the object.

1 Comment

When does it actually get released then? After addSubview is done running?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.