• 修改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;
    }
  • 相关阅读:
    分页实现
    jquery扩展提示框
    可拖拽可扩展面板
    单表查询结果转换成泛型集合
    压缩远程图片并返回
    windows下python安装架包的问题
    从网络上下载数据
    自己实现jquery
    如何利用拼音首字母查询数据库
    正则表达式
  • 原文地址:https://www.cnblogs.com/Apologize/p/6306690.html
Copyright © 2020-2023  润新知