Reputation: 54212
There are at least 3 methods of creating an IBOutlet
in Objective-C, for making iOS 10 App, in Xcode 8.
Method 1: in ViewController.h
@interface ViewController : UIViewController
@property (nonatomic, strong) UILabel *textLabel;
@end
Method 2: in the interface of ViewController.m
@interface ViewController () {
IBOutlet UILabel *textLabel;
}
@end
Method 3: in the interface of ViewController.m
, using @property
@interface ViewController ()
@property (nonatomic, strong) UILabel *textLabel;
@end
Given that the textLabel
has to be accessed & its text is needed to be updated frequently, which method is the correct way to do so?
Upvotes: 0
Views: 80
Reputation: 19602
Your code contains no proper IBOutlet
. Outlets are connections to Storyboard.
Method 1
This is a property. As it is in .h file, it can be reached from outside. The Objective-C pattern for public
.
Method 2
This is an iVar. Do not use iVars if you do not have to.
Method 3
This is a property. As it is in .m file, it can not be reached from outside. The Objective-C pattern for private
.
Method 4
A proper IBOutlet
looks like this:
@interface ViewController ()
@property (nonatomic, weak) IBOutlet UILabel *label;
@end
It is a simple property. You have to decide if you put it in .h or .m file depending on whether or not you want to publish it.
The IBOutlet
simply makes the property connect-able to Storyboard. It's an annotation for Xcode and does not alter the semantic of your code.
Edit 1:
As Sulthan correctly mentions in the comments:
In most situations the correct design pattern is to hide outlets because it's an implementation detail. External classes should not set data directly using views.
Edit 2:
Why "not to use iVars if you do not have to" (2)
Opinion based:
I consider it as good OOP practice to use getters & setters (and thus not to access the variables directly). Also code is easier to read as you know while reading what x = self.variable
(property) and x = variable
(local variable) are.
If you have to use iVars for some reason, it is common to (and I would recommend to) prefix the name with _
. x = _variable
(iVar).
Upvotes: 1
Reputation: 6157
That all depends on whether you need your outlet to be accessible to classes outside of the containing one; generally I would discourage this because it is good practice to keep your view controllers responsible for updating your UI and not pass this task around to other classes. With this being said, Method 3 would be the best option, however, if you do have to access your object from another class, then simply use Method 1 so it is exposed in your class header.
Method 2 utilises iVars rather than object properties and is not the proper way to declare outlets, it may even cause unexpected behaviour so it is best to avoid this method.
Upvotes: 2