Difference between declaring an ivar in @interface and putting variable in @implementation

前端 未结 3 1115
我在风中等你
我在风中等你 2021-02-02 03:47

What is the difference between declaring an ivar within an @interface versus putting a variable within an @implementation in a .m file?



        
3条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-02 04:29

    As far as I know, putting a variable declaration inside the @implementation is no different from putting it outside the implementation: It's not an ivar, it's just a variable declared at file scope.

    One use is for declaring the equivalent of C++ static members. For example:

    @implementation MyClass
    
    static int s_count = 0;
    
    - (id)init {
      if ((self = [super init]))
        ++s_count;
      return self;
    }
    
    - (void)dealloc {
      --s_count;
      [super dealloc];
    }
    

    Assuming init is your only initializer, then s_count will contain the total number of instances of MyClass that are active.

提交回复
热议问题