OC learn those things: @ property and @ synthesize

Source: Internet
Author: User

1. @ Property

Only use the @ interface keyword in the. h file

When the compiler encounters @ property, it automatically expands the declaration of the getter and setter methods.

// Equivalent @ property int age;-(INT) age;-(void) setage :( INT) newage;

Note: When @ property is detected in xcode4.5, @ synthesize is automatically added to the. M file.
Age = _ age. For example, if the. h file does not declare the _ age variable, the private member Variable _ age is automatically added to the. M file.

2. @ synthesize

Only use the @ implements keyword in the. M file.

When the compiler encounters @ synthesize, it is automatically expanded into the implementation of the getter and setter methods. By default, the member variables with the same name are accessed.

@ Synthesize age = _ age; indicates that the get and Set Methods access the member Variable _ age.

// Equivalent @ synthesize age = _ age;-(void) setage :( INT) newage {_ age = newage;}-(INT) Age {return _ age ;}

NOTE: If no member variable is found, a private member variable with the same name is automatically generated.

3. Complete use

Person. h file

@interface Person:NSObject {     int _ID;     float _weight; } @property int ID; @property float weight;  @end 

Person. M file

@implement Person  @synthesize ID = _ID; @synthesize weight = _weight;  @end 

4. Comprehensive use

The above @ property and @ synthesize keywords can be used in combination with the getter/setter method.

If the getter/setter method is manually implemented under certain special requirements, @ synthesize is invalid.

Person. h file

@interface Person:NSObject {     int _ID;     float _weight; } @property int ID; @property float weight;  @end 

Person. M file

@ Implement person-(void) setid: int newid {// In the getter/setter method, Special Operation _ id = newid * 100;}-(INT) id {return _ id;} @ end

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.