Search code examples
iosobjective-creactive-cocoa

does _ represent local variable?


I am pretty new to ReactiveCocoa and Objective-C. I see that in the following code there is usage of _subscribeCommand but there isn't a place where it was declared. It coincides with the subscribeCommand method. So is this a local variable?

- (RACCommand *)subscribeCommand {
  if (!_subscribeCommand) {
      NSString *email = self.email;
      _subscribeCommand = [[RACCommand alloc] initWithEnabled:self.emailValidSignal signalBlock:^RACSignal *(id input) {
          return [SubscribeViewModel postEmail:email];
      }];
  }
  return _subscribeCommand;
}

Full code were found in this tutorial http://codeblog.shape.dk/blog/2013/12/05/reactivecocoa-essentials-understanding-and-using-raccommand/


Solution

  • When you create a property on a class, Objective-C will create an instance variable with the same name as the property but with an underscore prefix. In the tutorial you link to there is a subscribeCommand property:

    @property(nonatomic, strong) RACCommand *subscribeCommand;
    

    Within the class you can access this property using the getters/setters using self.subscribeCommand or directly access the variable using _subscribeCommand.

    If you directly access the instance variable you are bypassing the getter/setter, whether an explicit getter/setter in the class or the implied getter/setter that enforces the property attributes (nonatomic, strong etc).

    In the example you link to, the subscribeCommand method is an explicit getter for the subscribeCommand property. There is no setSubscribeCommand method so the default setter will be used (which will enforce the strong and nonatomic attributes of the property).