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

前端 未结 3 1813
-上瘾入骨i
-上瘾入骨i 2020-12-09 10:45

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 sho

3条回答
  •  無奈伤痛
    2020-12-09 11:37

    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!

提交回复
热议问题