How to make a real private instance variable?

后端 未结 7 839
悲&欢浪女
悲&欢浪女 2020-11-28 04:33

I want to make an instance variable that can\'t be accessed from outside. Is something like that possible in objective-c? I remember Apple has private variables and stuff li

7条回答
  •  忘掉有多难
    2020-11-28 05:06

    You can not make a real private instance variable. Objective-C is a dynamic language and therefore it is possible to access any variable (even @private).

    My best approach:

    Use it in the implementation block of you .m file. Then it is not visible and block KVC, so that KVC will not work

    @implementation ClassName {
        // default to @protected
        // but the subclasses can't see ivars created in the implementation block
        float number;
    }
    
    + (BOOL)accessInstanceVariablesDirectly {
        return NO; // no KVC
    }
    
    @end
    

提交回复
热议问题