3

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.

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

So current best practice is properties > iVars?
You will find disagreement, but most style guides go this route. Generally, the overhead incurred from the synthesized getter/setter method calls is not noticeable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.