Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Properties and instance variable declaration

Tags:

objective-c

I notice that you can 'double declare' a variable in this way:

@interface A {
    NSString *instanceVariable;
}
@property (nonatomic, retain) NSString *instanceVariable;
@end

This has the same effect that just do:

@interface A {
}
@property (nonatomic, retain) NSString *instanceVariable;
@end

Why doesn't the compiler complain in situations like this?

like image 990
Bruno Berisso Avatar asked Aug 10 '26 06:08

Bruno Berisso


1 Answers

Because both ways are valid.

Declaring ivar via just declaring a property for it is a new language feature available starting objc 2.0

In "Run-time differences" section of "Objective-c programming language" reference stated:

For @synthesize to work in the legacy runtime, you must either provide an instance variable with the same name and compatible type of the property or specify another existing instance variable in the @synthesize statement. With the modern runtime, if you do not provide an instance variable, the compiler adds one for you.

like image 64
Vladimir Avatar answered Aug 11 '26 19:08

Vladimir