Search code examples
objective-cpublic-fields

How to access @public instance variable from another class in Objective-C?


I know it's possible to define public instance variable with @public keyword. However, Objective-C syntax does not allow accessing other class' variable. What features should I expected from @public Ivar? Or how do I access other class' Ivars?


Solution

  • Objective-C, as a superset of C, definitely does allow the access of public instance variables from outside the class's implementation. Now, the reason you may have heard that it isn't allowed is that it is highly discouraged. In most cases, if you want to access an instance variable outside an implementation context, you should be using accessors and mutators (properties).

    An Objective-C class really boils down to a plain-old C struct with an isa field (that's what makes it an object), where the public fields are accessible. Since when we are dealing with instances of classes, we are working a pointer to an object (special struct). Thus, we access public fields using ->.

    Here's an example:

    @interface SomebodyIsntEncapsulating : NSBadIdea {
      @public
      NSString *badIdea;
      BOOL shouldntDoIt;
    
      @protected
      NSString *ahThatsBetterThankGod;
    
      @private
      NSString *sweetThanksNowEvenMySubclassesCantTouchMe;
    }
    

    Now, in some completely different context, we could have:

    SomebodyIsntEncapsulating *whatOh = [[SomebodyIsntEncapsulating alloc]
                                           initWithDanger:kDangerLevelEpicBraceYourself];
    whatOh->badIdea = [@"I'm a public field. Make sure to retain or copy me!" copy];
    NSLog(@"Please! Write some accessors and mutators!: %@", whatOh->badIdea);
    

    I hope that helped you!