How to make a real private instance variable?

后端 未结 7 775
悲&欢浪女
悲&欢浪女 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:25

    You can use the @private keyword inside the {} to make all subsequent variable declarations private. The default visibility is @protected (which is similar to protected in Java) and that generally works well. You'd have to specifically declare a variable as @public for it to be directly accessible outside the class.

    This Apple documentation has further details about variable scope and visibility.

    There is also a difference between "private API" and private variables. In Objective-C, you cannot make methods private — anyone can call any method. There are several ways to create "secret" methods, but that's somewhat out of the scope of this question. Here are a few related SO questions:

    • About private instance variables in Objective-C
    • What does “@private” mean in Objective-C?
    • Is it possible to declare a method as private in Objective-C?
    • Best way to define private methods for a class in Objective-C

    As far as the leading _ in front of variables, be aware that Apple also reserves this prefix for "private" methods. The best way to guarantee you avoid problems is to use normal naming conventions for your own variables and methods. However, unless you subclass something from Cocoa (other than NSObject) you can be fairly confident that you won't run into problems.

    0 讨论(0)
提交回复
热议问题