1

I know this question has been asked before but possibly not in the same context. My question is that I have a singleton class that is only dipatched_once in the lifetime of the app. In the class I have some methods that are accessing the instance variables and acting upon if they have been set on the instance. This is example of how I am attempting to access them:

// .m file:

Interface:

@property (nonatomic, assign, readwrite) BOOL userLoggedIn; 

Implementation: // method:

-(void)someMethod{ if(!_userLoggedIn){ } else { } } 

I know I can also use self to evaluate the value like this:

-(void)someMethod{ if(self.userLoggedIn){ } else { } } 

Wondering which is correct way of accessing the value? I am not synthesizing the properties since they are all declared in the interface only in the .m file. Thanks for the help!

3
  • It depends, but if you have -(BOOL)userLoggedIn{} implemented, that could change the behavior. Commented Jan 24, 2017 at 19:06
  • Possible duplicate of iOS: Usage of self and underscore(_) with variable Commented Jan 24, 2017 at 19:12
  • If userLoggedIn is only defined for use in the implementation and you are using direct access to the variable, is there a reason you are declaring a property at all? Why not just use an instance variable (as in @implementation { BOOL userLoggedIn; } ...? Commented Jan 24, 2017 at 22:22

1 Answer 1

6

It depends.

Do you want the accessor invoked or not? _variable is direct access. self.variable invokes -variable, which is automatically synthesized by the compiler.

The former does not trigger KVO when the value changes. The latter does. That may be a feature or anti-feature.

But, whichever you choose, especially for write operations, make it consistent or else you'll be tracking down bugs in the future.


A general rule:

  • access directly in -init/-dealloc

  • access through setter/getter (dot syntax) everywhere else


Note also that direct access will not respect atomic.

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

3 Comments

Thanks much appreciated!
What do you mean by invoked or not invoked variables?
@randomorb2110 _variable = 10; directly sets the instance variable. self.variable = 10; translates to [self setVariable:10];. One is a direct write, one calls the setter method.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.