修改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; }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM