Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

@interface MyClass : NSObject {
  int num;
}
- (void)doSomething;
@end

vs.

@implementation MyClass   
int num2;

- (void)doSomething {
  num = 137;
  num2 = 138;
}
@end

Is there ever a time when you want to put a variable within the @implementation?

like image 830
nickfox Avatar asked Apr 06 '11 00:04

nickfox


1 Answers

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.

like image 133
drewag Avatar answered Sep 20 '22 00:09

drewag