Difference between @interface declaration and @property declaration
iphone, objective-c, properties
Solution
Here, you're declaring an instance variable named `aVar`:
@interface myclass : UIImageView {
int aVar;
}
You can now use this variable within your class:
aVar = 42;
NSLog(@"The Answer is %i.", aVar);
However, instance variables are private in Objective-C. What if you need other classes to be able to access and/or change `aVar`? Since methods are public in Objective-C, the answer is to write an accessor (getter) method that returns `aVar` and a mutator (setter) method that sets `aVar`:
// In header (.h) file
- (int)aVar;
- (void)setAVar:(int)newAVar;
// In implementation (.m) file
- (int)aVar {
return aVar;
}
- (void)setAVar:(int)newAVar {
if (aVar != newAVar) {
aVar = newAVar;
}
}
Now other classes can get and set `aVar` via:
[myclass aVar];
[myclass setAVar:24];
Writing these accessor and mutator methods can get quite tedious, so in Objective-C 2.0, Apple simplified it for us. We can now write:
// In header (.h) file
@property (nonatomic, assign) int aVar;
// In implementation (.m) file
@synthesize aVar;
...and the accessor/mutator methods will be automatically generated for us.
To sum up:
`int aVar;` declares an instance variable `aVar`
`@property (nonatomic, assign) int aVar;` declares the accessor and mutator methods for `aVar`
`@synthesize aVar;` implements the accessor and mutator methods for `aVar`
Problem
I'm new to C, new to objective C. For an iPhone subclass, Im declaring variables I want to be visible to all methods in a class into the @interface class definition eg ``` @interface myclass : UIImageView { int aVar; } ``` and then I declare it again as ``` @property int aVar; ``` And then later I ``` @synthesize aVar; ``` Can you help me understand the purpose of three steps? Am I doing something unnecessary? Thanks.