本節通過 main 函數演示屬性的三種賦值方式:setter 方法、點語法,以及 KVC 賦值。
#import <Foundation/Foundation.h>
#import "Car.h"
#import "Phone.h"
int main(int argc, const char * argv[]) {
Car *c1 = [[Car alloc] init];
Car *c2 = [[Car alloc] initWithBrand:@"QQ" price:40000.0];
// 給 c1 設置品牌和價格(setter 方法)
[c1 setBrand:@"蘭博基尼"];
[c1 setPrice:3000000.0];
NSLog(@"%@ %.2f", [c1 brand], [c1 price]);
// 創建手機
Phone *p1 = [[Phone alloc] init];
// 方式一:setter 方法
// [p1 setBrand:@"諾基亞"];
// [p1 setColor:@"白色"];
// [p1 setPrice:2000.0];
// [p1 setAddress:@"中國"];
// 方式二:點語法代替 setter
p1.brand = @"諾基亞";
p1.color = @"白色";
NSLog(@"手機是%@品牌的", p1.brand);
// 方式三:KVC 賦值(以間接方式對屬性賦值)
[p1 setValue:@"摩托羅拉" forKey:@"brand"];
[p1 setValue:@"墨綠色" forKey:@"color"];
NSLog(@"手機是%@品牌的", p1.brand);
return 0;
}
通過對比可以發現,點語法本質上是 setter/getter 的簡化寫法,而 KVC(Key-Value Coding)則提供了以字符串 key 間接訪問屬性的能力,靈活性更強。