Best way of declaring private variables in cocoa

前端 未结 1 567
旧巷少年郎
旧巷少年郎 2020-12-17 05:17

I would like to know what the recommendations are for declaring private instance variables in cocoa. This question is in the context of developing apps on the iPhone.

相关标签:
1条回答
  • 2020-12-17 06:09

    Your three options have different semantics:

    1. This creates an instance variable. Without garbage collection you need to retain/release objects you store into myPrivateVar.
    2. This does not define an instance variable at all. Variables defined outside of the @interface and the scope of many method (or function) definitions are "global" - effectively class variables (which Objective-C has no special syntax for). Such a variable is shared by all instances of MyClass.
    3. The difference between using a property (with or without the variable being explicitly declared) comes down to memory management. Defined as you have with retain means that there is no need for retain/release when you do not have garbage collection.

    So don't use 2! Option 3 clearly has benefits if you don't have garbage collection, it provides some measure of abstraction over option 1, and is more costly - though you will probably not notice the difference outside of computationally intensive code which access the variable heavily.

    Update 2015

    Where garbage collection is used above ARC (automatic reference counting) is now more applicable (garbage collection is now deprecated). Also there is now a fourth option:

    1. Declare them in the implementation section of the m file:

      @implementation MyClass  
      {
         NSObject * myPrivateVar;
      }
      

      Unlike option (2) this does declare an instance variable. The variable is private to the implementation, and with ARC memory management is automatic. The choice between this and (3) [which incidentally also no longer requires the @synthesize] comes down to choice and need; properties give you dot syntax, the ability to customise the setter and/or getter, and the copy attribute for automatic copy on assignment, but if you need none of these you can simply use the an instance variable.

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