zoukankan      html  css  js  c++  java
  • 修改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;
    }
  • 相关阅读:
    jdk7_ConcurrentHashMap 图示
    Teradata 日期函数
    Teradata正则表达式
    Teradata sql去除字段中的字母/数字
    sql查询连续3天有交易记录的客户
    批量生成sql查询语句
    sql查询字段中是否含有字母/数字/符号
    sql查询每个人最新的2个电话号码
    python连接Teradata数据库
    dos命令获取文件行数
  • 原文地址:https://www.cnblogs.com/Apologize/p/6306690.html
Copyright © 2011-2022 走看看