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

后端 未结 5 2285
小蘑菇
小蘑菇 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 13:55

    NSObject conforms to the NSKeyValueCoding informal protocol. This defines setValue:forKey: and valueForKey:. setValue:forKey: and valueForKey: search for a way to access the value of the key according to specific search rules which includes directly accessing the instance variable. This direct accessing is controlled by accessInstanceVariablesDirectly method which is a part of the NSKeyValueCoding informal protocol, which by default returns YES, allowing those methods to directly access the instance variables and as a result not really making them private as such. They are still private from direct access.

    To resolve this, you will have have to override the methods mentioned above and defined in the NSKeyValueCoding informal protocol to prevent their access.

    As mentioned by Abizern, properties for private variables are still accessible since Objective-C has no concept of private methods.

提交回复
热议问题