readonly:只读属性,只生成getter方法,也就是说只能访问变量,不能修改。
那我们如果想要改变类中声明为readonly的属性值该怎么做呢
@interface Person : NSObject @property (nonatomic, copy, readonly) NSString *nickname; @end
直接修改会报错:
可以用kvc来给声明为readonly的属性重新赋值
- (void)viewDidLoad { [super viewDidLoad]; Person *p = [[Person alloc] init]; //p.name = @"cc"; [p setValue:@"cc" forKey:NSStringFromSelector(@selector(nickname))]; NSLog(@"\n p.name: %@ \n",p.nickname); }
打印:
2021-05-04 18:50:16.403238+0800 ReadonlyDemo[83730:9454419] p.name: cc