Do ivars need to be declared in @interface to match properties?

Possible duplicate:
Properties and instance variables in Objective-C 2.0

I am confused by these two code segments:

Firstly:

//.h @interface Student : NSObject { } @property (nonautomic, copy) NSString *name; @property (nonautomic, retain) NSNumber *age; @end //.m @implementation Student @synthesize name; @synthesize age; @end 

Secondly:

 //.h @interface Student : NSObject { NSString *name; // <<============ difference NSNumber *age; // <<============ difference } @property (nonautomic, copy) NSString *name; @property (nonautomic, retain) NSNumber *age; @end //.m @implementation Student @synthesize name; @synthesize age; @end 

Both can work. So what is the need to declare variables in {} ?

+4
source share
3 answers

Starting with the modern runtime (x86_64 and ARM6 ... and iOS Simulator), you no longer need to declare synthesized ivars. In the first example, @synthesize adds an instance variable for you.

+10
source

Agree with @Joshua. I was also embarrassed by this in the beginning. This is basically an old agreement versus a new agreement after runtime updates. I think Apple realized that the ivars declaration was redundant when you were going to declare @property, so why not let @synthesize take care of it when it creates setters and getters. Another expression for us to write, yay!

(Some of these changes were explained in one of the early WWDC videos ... I think)

0
source

Objective-C Programming Language: Property Implementation Guidelines

There are differences in the behavior of the access synthesizer, depending on the execution time (see also "Run-time difference"):

  • For an obsolete runtime, instance variables should already be declared in the @interface block of the current class. If there is an instance variable with the same name as the property, and if its type is compatible with the type of the properties, it is used, otherwise you will get a compiler error.

  • For modern runtime environments (see "Runtime and Platform Versions" in the Objective-C Runtime Programming Guide), instance variables are synthesized as needed. If an instance variable with the same name already exists, it is used.

0
source

Source: https://habr.com/ru/post/1383938/


All Articles