IOS Instance Variables

Simple question, I just would like to hear what other people are doing and what the best practice might be. To clear up some things.

When declaring an instance variable in one of my view controllers. Where is the right place for the announcement? I want an instance variable to be available to all methods / functions in a view controller

I've seen how this is done in the file .h

in curly braces after @interface

:

@interface ViewController : UIViewController {
    NSString *test3;
}

      

I've seen how this is done in the file .m

in curly braces after @interface

:

@interface ViewController () {
    NSString *test1;
}

      

And I saw how it is done in the file .m

in curly braces after @implementation

:

@implementation ViewController {
    NSString *test2;
}

      

What's the best practice? Is there a difference? If so, what might they be, and what makes one path better than the other?

All help would be appreciated, Thanks.

+3


source to share


1 answer


Any of these will work, but the property is currently best used. If you only want it to be available inside your class:

@interface ViewController ()

@property (copy, nonatomic) NSString *test1;

@end

      

Access it like this:

self.test1 = @"Hello, world";

      

But, if you want it to be available to other classes as well, put it in a public interface:

@interface ViewController : UIViewController

@property (copy, nonatomic) NSString *test1;

@end

      



And then enter it like this:

someInstanceOfViewController.test1 = @"Hello, world";

      

If you need to access an instance variable directly (and this only applies to a class in most cases), for example, if you create a custom setter, the compiler will automatically synthesize an ivar, which is the name of your property, prefixed with an underscore:

- (void)setTest1:(NSString *)test1
{
    _test1 = [test1 copy];
}

      

Note. copy

is that you can install test1

into an instance NSMutableString

, and you probably don't want its contents to get mutated from under you. When you override the setter as above, you must enforce this semantics copy

.

+3


source







All Articles