Difference between @interface declaration and @property declaration

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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)