1 #import "Cat.h" 2 3 @interface Cat () 4 5 @property (nonatomic, copy) NSString *name; 6 7 @end 8 9 @implementation Cat{ 10 int age; 11 } 12 13 -(ins ...
1 #import "Cat.h" 2 3 @interface Cat () 4 5 @property (nonatomic, copy) NSString *name; 6 7 @end 8 9 @implementation Cat{ 10 int age; 11 } 12 13 -(instancetype)initWithName:(NSString *)string{ 14 self = [super init]; 15 if (self) { 16 _name = string; 17 age = 1; 18 } 19 return self; 20 } 21 22 @endCat
Cat *cat = [[Cat alloc]initWithName:@"大懶貓"]; NSLog(@"第一種,通過kvc獲取與修改屬性以及實例變數age\n\n"); //第一種,通過kvc獲取與修改屬性以及實例變數age NSString *cat_name = [cat valueForKey:@"name"]; [cat setValue:@"大花貓" forKey:@"name"]; NSString *cat_name_modified = [cat valueForKey:@"_name"];//key值為name與_name都可以,因為程式運行時會去類中找,先找同名的,再找帶有下劃線_的,找不到就報錯。 NSLog(@"name修改前:%@, 修改後:%@",cat_name,cat_name_modified); //列印結果:name修改前:大懶貓, 修改後:大花貓 int age = [[cat valueForKey:@"age"]intValue]; [cat setValue:@2 forKey:@"age"]; int age_mod = [[cat valueForKey:@"age"]intValue]; NSLog(@"age修改前:%d, 修改後:%d",age,age_mod); //列印結果:age修改前:1, 修改後:2 NSLog(@"\n\n第二種,通過runtime獲取與修改屬性\n\n"); //第二種,通過runtime獲取與修改屬性 Ivar m_name = class_getInstanceVariable([Cat class], "_name"); cat_name = (NSString *)object_getIvar(cat, m_name); NSLog(@"name修改前:%@",cat_name); //列印結果:name修改前:大花貓 object_setIvar(cat, m_name, @"大臉貓"); cat_name = (NSString *)object_getIvar(cat, m_name); NSLog(@"name修改:%@",cat_name); //列印結果:name修改:大臉貓