修改readonly属性的值

一般情况下,readonly属性的值是无法修改的,但可以通过特殊方式修改。
定义一个student的类,其中name属性为readonly类型的变量

@interface JFStudent : NSObject

@property(nonatomic,copy,readonly) NSString *hisName;

@property(nonatomic,copy) NSString *age;

-(instancetype)initWithName:(NSString *)name age:(NSString *)age;

@end
@implementation JFStudent

-(instancetype)initWithName:(NSString *)name age:(NSString *)age{
    if (self = [super init]) {
        _hisName = name;
        _age = age;
    }
    return self;
}

@end

然后定义一个JFStudent类型的变量

JFStudent *stu = [[JFStudent alloc]initWithName:@"tom" age:@"11"];
NSLog(@"修改前++++++++%@",stu.hisName);

修改hisName变量,会提示出错。

这时可以用kvc来设置

[stu setValue:@"胡说" forKey:NSStringFromSelector(@selector(hisName))];
NSLog(@"修改后----------------%@",stu.hisName);

打印结果为:

若age为NSInteger属性,

@property(nonatomic,assign,readonly) NSInteger age;

则可以用

[stu setValue:@(20) forKey:NSStringFromSelector(@selector(age))];

打印结果为

若想禁止kvc修改readonly属性的值,则可以在定义readonly属性的类中添加该方法

//默认返回为YES,表示可允许修改。改为NO即可
+(BOOL)accessInstanceVariablesDirectly{
    return NO;
}
原文地址:https://www.cnblogs.com/Apologize/p/6306690.html