The role of the Get/set method when a property in a class is set to private, you need to use the Get/set method to access the property.set () is assigned to a property, and get () is the value of the propertyproperties that are set and accessed are generally privateIt is primarily a function of encapsulation that does not allow direct manipulation of attributesset () and get () do not necessarily exist at the same time, see Program Requirements
File "PERSON.M"#import <Foundation/Foundation.h>
@interfacePerson :NSObject
{
intAge ;
intheight;
intweight;
}
The substitution method of the//get set method. As you can see, the Set/get method creation is simple, but when there are many properties, a lot of redundant code brings //The workload is hehe. X-code provides a quick way to create with the properties of the Get/set method directly with "@property type name". //This eliminates the process of knocking each property Get,set method, which is very quick to use. @propertyintAge ;
@propertyintheight;
@property intweight;
//get Setmethod,
-(int) age;
-(void) Setage: (int) NewAge;
-(int) height;
-(void) SetHeight: (int) Newheight;
-(int) weight;-(void) setweight: (int) newweight;
//Output-(void) display; @end
File "PERSON.M"#import"Person.h"
@implementation Person
//corresponding to the property, the Set/get implementation method can be simplified to the following three lines of code. The form is "@Synthesize attribute"@synthesizeAge ;
@synthesizeheight;
@synthesizeweight;
//set, get method implementation-(int) Age
{
return Age;
}
-(void) Setage: (int) NewAge
{
Age= NewAge;
}
-(int) Height
{
returnHeight;
}
-(void) SetHeight: (int) Newheight
{
Height= Newheight;
}
-(int) Weight
{
returnWeight;
}
-(void) Setweight: (int) Newweight
{
Weight= Newweight;
}
-(void) display
{
NSLog(@ "age =%i, height =%i, weight =%i", Age,Height,Weight);
}
@end
File "mail.m" #import <Foundation/Foundation.h>
#include"Person.h"
intMain (intargc,Const Char* argv[]) {
@autoreleasepool{
//Insert code here ...
NSLog(@ "Hello, world!");
Person*personone = [[ PersonAlloc]Init];[Personone display];[PersononeSetage: -];[Personone Setweight: -] ;[Personone setheight: 175]; [personone display]; }
return0;}
Output Result:
2014-11-25 10:50:29.894 accesser[731:303] Hello, world!
2014-11-25 10:50:29.896 accesser[731:303] Age = 0, height = 0, weight = 0
2014-11-25 10:50:29.897 accesser[731:303] Age =, height = 175, weight =
"Object-c" Get/set method