Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should every IBOutlet have a property?

We create property for a variable for using it in some other view. Same we do for IBOutlets. But not always for using them. Is it necessary to create property for each IBOutlet we just created it our xib? Or is it only a good practice to do so?

like image 839
Nitish Avatar asked Dec 07 '22 20:12

Nitish


2 Answers

I like to look at it is in terms of ease of memory management, and external access. If you need to access it externally, obviously make a property. (Yes ease of memory management, if it's easy you won't mess it up, if you don't mess it up it doesn't become a bug later)

80% of the time my view controller has the IBOutlets and nobody else accesses them, therefore ivars work. The problem is that when you don't use @property, the assigned value is still retained. Then you need to remember to release it even though you didn't retain it yourself, which I found counter-intuitive.

For that reason I usually use @property (assign) for the ones I won't be changing, and @property (retain) for everything else, and never declare IBOutlets directly as ivars.

Example:

@interface something : NSObject {
    //This one needs to be RELEASED then set to nil in both viewDidUnload, and dealloc.
    IBOutlet UILabel * myLabel;
    //also cannot be accessed outside of "something" class (technically it can, but don't do that)
    //I NEVER declare my outlets this way.
}

//This one can just be set to nil in viewDidUnload and dealloc
@property (nonatomic, retain) UILabel * myOtherLabel;
//it can also be accessed from mySomething.myOtherLabel by any other class.

//This one just works. I don't own it, the view owns it, so I don't retain/release.
@property (nonatomic, assign) UILabel * myOtherOtherLabel;
//It also provides access to outsiders.
//I wouldn't recommend using this type if you want to change the value though.
like image 63
Alex Gosselin Avatar answered Jan 03 '23 22:01

Alex Gosselin


It is not necessary to create a property for each IBOutlet.

Specifically, if you access the outlet only from the class where it is declared, you do not strictly need the property. If you have a property, you get the advantages that properties offer, but you could always directly refer the outlet directly.

If you plan to access the outlet from another class, then a property is useful so you don't have to define yourself setter and getter methods.

like image 45
sergio Avatar answered Jan 03 '23 20:01

sergio