Simple question, I would just like to hear what other people do, and what best practice might be. To clear some things up.
When declaring an instance variable in one of my view controllers. Where is the proper place to declare it? I want the instance variable to available to all methods/function in the view controller
I've seen it done this way, in the .h file in curly braces after the @interface:
@interface ViewController : UIViewController {
NSString *test3;
}
I've seen it done this way, in the .m file in curly braces after the @interface:
@interface ViewController () {
NSString *test1;
}
And I've seen it done this way, in the .m file in curly braces after the @implementation:
@implementation ViewController {
NSString *test2;
}
What is the best practice? Is there any difference? If so what may they be, and what makes one way better than another?
All help will be appreciated, Thanks.
Any of those will work, but current best practice is to use a property. If you want it to be accessible only inside your class:
@interface ViewController ()
@property (copy, nonatomic) NSString *test1;
@end
An access it like this:
self.test1 = @"Hello, world";
But, if you want it to be accessible to other classes as well, put it in the public interface:
@interface ViewController : UIViewController
@property (copy, nonatomic) NSString *test1;
@end
And then access it like this:
someInstanceOfViewController.test1 = @"Hello, world";
If you need to access the instance variable directly (and this applies only inside the class in most cases), for example if you are making a custom setter, the compiler will auto-synthesize an ivar that is the name of your property prefixed with an underscore:
- (void)setTest1:(NSString *)test1
{
_test1 = [test1 copy];
}
Note: the copy is because you might set test1 to an instance of NSMutableString, and you probably don’t want its contents getting mutated out from under you. When you override the setter, as above, you have to enforce this copy semantic yourself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With