Objective-c: why private ivars are not hidden from the outside access when using KVC

后端 未结 5 2297
小蘑菇
小蘑菇 2020-12-15 13:13

After trying to access ivars using KVC, I have noticed that there was no protection on private and protected ivars. It doesn\'t matter what I put a in front of the ivar (pri

5条回答
  •  余生分开走
    2020-12-15 14:08

    I'll add my two cents to this old question.

    I think the @private, @protected is there also to prevent access to a variable using the '->' operator.

    Imagine you have a iVar called myPrivateVar declared like below:

    @interface MyClass:NSObject{
      @public
        NSArray *myPrivateVar;
    }
    

    So even if you implement the below class method to return NO and don't have accessors declared for the iVar:

    +accessInstanceVariablesDirectly{
        return NO;
    }
    

    the variable is still accessible if you use myClassObj->myPrivateVar;

    On the other hand if you just make the @public to @private and don't implement accessInstanceVariableDirectly, the variable is still accessible by using KVC:

    [myClassObj valueForKey:@"myPrivateVar"];
    

    (and not accessible via myClassObj->myPrivateVar)

    So to make your iVar completely private it should be declared as @private and also accessInstanceVariablesDirectly should be implemented to return NO.

提交回复
热议问题