object-c學習筆記:屬性變數(property)

來源:互聯網
上載者:User

什麼是property?

是一種代碼產生機制,能夠產生不同類型的getter/setter函數,特別是如果你想要用點(.)操作符號來存取變數的話,你就能必須使用property。

 

如何使用?

用法是固定的,注意下property後面小括弧了跟的參數列表,nonatomic代表非原子性,既不支援多線程的同步,mac上可以根據具體情況考慮,IPhone上就加上把,retain代表對setter的對象加上一個retain操作,同時也會release原有的object,copy顧名思義就是copy setter中參數的對象。看下面的例子:

代碼

@interface Engine : NSObject
{
}
@end

@implementation Engine

- (NSString*) description
{
return (@"engine");
}

@end

@interface Tier : NSObject
{
}
@end


@implementation Tier

- (NSString*) description
{
return (@"tier");
}

@end

@interface Car : NSObject
{
int tier_num;
float engine_power;
NSString* name;
Engine* engine;
Tier* tier;
}

@property (nonatomic) int tier_num;
@property (nonatomic) float engine_power;
@property (nonatomic, copy) NSString* name;
@property (nonatomic, retain) Engine* engine;
@property (nonatomic, retain) Tier* tier;

@end

@implementation Car

@synthesize tier_num;
@synthesize engine_power;
@synthesize name;
@synthesize engine;
@synthesize tier;

- (id) init
{
if (self = [super init]) {
tier_num = 4;
engine_power = 100;
name = @"BMW";
}
return self;
}

@end


int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

Car* car = [[Car alloc] init];
NSLog(@"number of tiers is %d\n", car.tier_num);
NSLog(@"car's name is %a\n", car.name);
car.name = @"Mazd";

Engine* newEngine = [[Engine alloc] init];
car.engine = newEngine;

// insert code here...

[pool drain];
return 0;
}

 

額外的內容

預設的propety變數,總是可讀寫的,如果需要唯讀控制,就用readonly,這時編譯器不會產生setter方法,如

@property (readonly) float something;

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.