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

后端 未结 5 2268
小蘑菇
小蘑菇 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:05

    Don't declare a @property for an iVar if you really want it to remain private.

    It isn't the iVar that is no longer private. The Objective-C runtime doesn't have a concept of private methods. Since using @property and @synthesize generates KVC compliant accessor methods, you can always call the methods, regardless of whether the backing iVar is private or not.

    But it isn't as bad as you think. Using the methods you have doesn't directly change the iVar - it goes through the setters. If you need extra protection you can write your own setter that implements whatever protection you need.

    If you just declare an iVar as @private and don't make it KVC compliant - it will remain private. Of course; you then can't use KVC or KVO on that iVar, but if you wanted to be able to use them you shouldn't be declaring it as a private iVar.

提交回复
热议问题