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

前端 未结 3 1060
我在风中等你
我在风中等你 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:37

    The difference between using an ivar and declaring a variable inside the implementation is that the variable within the implementation is at file scope and global. That means all instances (and any static methods) will share the same variable; i.e. if one instance of your object changes the variable, it will change it for all instances.

    The use case for defining it at file scope is to store things for static methods (methods that act directly on the class instead of an instance of the class). A really common use case for this is the Singleton design pattern. You can define a static instance of your class within this file so that at any time, you can ensure you are accessing the same instance. You can provide a static method that returns this instance so any object in your code can access that same object by calling the method directly on your class.

    Update 4/17/14

    Common practice now is to use Properties. This creates getters and setters for you automatically making the class more extensible (if you decide to change the way a property works, perhaps you want to change it to always be calculated on the fly, the public interface of the class does not need to change).

    You can use private class extensions to declare "private" properties and methods. This has the effect of protecting certain properties and methods from being accessed by outside classes.

提交回复
热议问题