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 hav开发者_开发百科e 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];
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.
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.
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.
精彩评论