0

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!

rmaddy
  • 314,917
  • 42
  • 532
  • 579
randomorb2110
  • 259
  • 1
  • 4
  • 9
  • It depends, but if you have `-(BOOL)userLoggedIn{}` implemented, that could change the behavior. – Larme Jan 24 '17 at 19:06
  • Possible duplicate of [iOS: Usage of self and underscore(\_) with variable](http://stackoverflow.com/questions/12175229/ios-usage-of-self-and-underscore-with-variable) – holex Jan 24 '17 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; } ...`? – CRD Jan 24 '17 at 22:22

1 Answers1

5

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.

bbum
  • 162,346
  • 23
  • 271
  • 359