Ios obtains and modifies class private attributes and instance variables, and ios instances
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: @ "lazy Cat"]; NSLog (@ "first, use kvc to obtain and modify attributes and the instance variable age \ n "); // first, use kvc to obtain and modify attributes and the instance variable age NSString * cat_name = [cat valueForKey: @ "name"]; [cat setValue: @ "" forKey: @ "name"]; NSString * cat_name_modified = [cat valueForKey: @ "_ name"]; // if the key value is "name" or "_ name", you can find the key value in the class before running the program. If the key value is not found, the system returns an error. NSLog (@ "before name modification: % @, after modification: % @", cat_name, cat_name_modified); // print the result: Before name modification: lazy cat, after modification: big cat int age = [[cat valueForKey: @ "age"] intValue]; [cat setValue: @ 2 forKey: @ "age"]; int age_mod = [[cat valueForKey: @ "age"] intValue]; NSLog (@ "age: % d before modification, % d after modification", age, age_mod); // print the result: age before modification: 1. After modification: 2 NSLog (@ "\ n Second, get and modify attributes \ n" Through runtime); // second, use runtime to obtain and modify the attribute Ivar m_name = class_getInstanceVariable ([Cat class], "_ name"); cat_name = (NSString *) object_getIvar (cat, m_name ); NSLog (@ "name before modification: % @", cat_name); // print the result: name before modification: Big cat object_setIvar (cat, m_name, @ "big face cat "); cat_name = (NSString *) object_getIvar (cat, m_name); NSLog (@ "name Change: % @", cat_name); // print the result: name Change: Big face cat