get /set 方法的作用
當類中的屬性被設置爲私有時,需要用get/set方法來存取屬性。
set()是給屬性賦值的,get()是取得屬性值的
被設置和存取的屬性一般是私有
主要是起到封裝的作用,不允許直接對屬性操作
set()和get()不一定同時存在,看程序需求
File “person.m”
#import <Foundation/Foundation.h>
@interface person : NSObject
{
int age ;
int height ;
int weight ;
}
//get set 方法的代替方法。可以看到,set/get方法創建雖然很簡單,但是當屬性很多的時候,大量冗餘的代碼帶來
//的工作量就呵呵了。X-code 提供了一個快捷的辦法,需要用get/set方法的屬性直接用“@property 類型 name ”創建。
//這樣就省去了自己敲各個屬性get,set 方法的過程,用起來非常的快捷。
@property int age
;
@property int height ;
@property int weight ;
//get set 方法,
-(int)age;
-(void)setAge:(int)
newAge;
-(int)height;
-(void)setHeight:(int)
newHeight;
-(int)weight;
-(void)setWeight:(int)
newWeight;
//輸出
-(void)display;
@end
File “person.m”
#import "person.h"
@implementation person
//與property相對應的,set/get實現方法可以簡化爲以下三行代碼。形式爲“@Synthesize 屬性”
@synthesize age ;
@synthesize height ;
@synthesize weight ;
//set、get方法實現
-(int)age
{
return age;
}
-(void)setAge:(int)newAge
{
age = newAge ;
}
-(int)height
{
return height ;
}
-(void)setHeight:(int)newHeight
{
height = newHeight ;
}
-(int)weight
{
return weight ;
}
-(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"
int main(int argc, const char *
argv[]) {
@autoreleasepool {
// insert code here...
NSLog(@"Hello, World!");
person *personone = [[person alloc ]init];
[personone display];
[personone setAge: 18];
[personone setWeight: 50]
;
[personone setHeight: 175]
;
[personone display];
}
return 0;
}
輸出結果:
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 = 18 , height = 175 , weight = 50