holydancer原創,如需轉載,請在顯要位置註明:
轉自holydancer的CSDN專欄,原文地址:http://blog.csdn.net/holydancer/article/details/7355833
在objective-c中,我們可以用new簡單的代替alloc init,我們今天介紹的是類似於new這種簡易用法的另一種OC特性,用@property,@synthesize來代替get,set方法,用起來很簡單,可以省掉很多的代碼量,當需要用SET,GET方法的地方,我們可以用@property,@synthesize來簡單的代替,這時系統會自動給我們產生該變數的set,get方法,@property對應方法的聲明部分,@synthesize對應方法的實現部分。
Human.h:
#import <Foundation/Foundation.h>@interface Human : NSObject{ int age; float height;}//這裡用@property表示,代表了age和height的set,get方法的聲明@property int age;@property float height;@end
Human.m:
#import "Human.h"@implementation Human//這裡用@synthesize表示age,height變數的set,get方法的實現。@synthesize age;@synthesize height;@end
main.m:
#import <Foundation/Foundation.h>#import "Human.h"int main(int argc, const char * argv[]){ NSAutoreleasePool *pool=[[NSAutoreleasePool alloc]init]; Human *human = [[Human alloc]init]; //“.”在等號左邊,相當於set方法。 human.age=20; //等價於[human setAge:20] human.height=60.50; //“.”在等號右邊,相當於get方法。 float tmp=human.height;//等價於 float tmp = [human height] NSLog(@"年齡%d,身高%f",human.age,tmp); [human release]; [pool release];//相當於對池中每個對象執行了一次release; }
輸出語句:
2012-03-15 10:11:34.052 String[325:403] 年齡20,身高60.500000
這時系統會自動產生age,height的set,get方法,可以直接使用,那還有一種情況,如果我只想讓age有get方法,沒有set方法怎麼辦,也就是說在初始化裡給一個預設值,而這個值只能被調用,不能被修改,用@property這種方式可以嗎。答案是肯定的,因為@property給我們提供了類似參數的一種可選項,關鍵詞是readonly,readwrite,分別對應著只能讀不能修改和讀寫均可,一般我們不設定readwrite,因為預設就是讀寫狀態。看代碼:
Human.h:
#import <Foundation/Foundation.h>@interface Human : NSObject{ int age; float height;}//這裡用@property表示,代表了age和height的set,get方法的聲明@property (readonly)int age;@property float height;@end
Human.m:
#import "Human.h"@implementation Human//重寫init方法給age賦初值-(id)init{ if(self=[super init]) { age=20; } return self;}//這裡用@synthesize表示age,height變數的set,get方法的實現。@synthesize age;@synthesize height;@end
main.m:
#import <Foundation/Foundation.h>#import "Human.h"int main(int argc, const char * argv[]){ NSAutoreleasePool *pool=[[NSAutoreleasePool alloc]init]; Human *human = [[Human alloc]init]; human.height=60.5; //human.age=30; 該行如果不注釋是會報錯的,即age只有get方法,沒有set方法 NSLog(@"年齡age=%d",human.age); [human release]; [pool release];//相當於對池中每個對象執行了一次release; }
輸出:
2012-03-15 10:32:11.497 String[360:403] 年齡age=20
關鍵字:objective-c ,objective c , oc ,@property , @synthesize