一般通過KVC修改readonly屬性值熊昌。如果修改NSUInteger類型的值,則傳入一個(gè)NSNumber的對(duì)象,Objective-C會(huì)處理好一切漾根。
#import <Foundation/Foundation.h>
@interface Student : NSObject
@property(nonatomic,copy,readonly)NSString *nickName;
@property(nonatomic,copy,readonly)NSString *studentNumber;
@property(nonatomic,assign,readonly)NSUInteger age;
-(instancetype)initWithStudentNumber:(NSString *)studentNumber nickName:(NSString *)nickName age:(NSUInteger)age;
-(void)study;
-(void)goSchool;
@end
#import "Student.h"
@implementation Student
-(instancetype)initWithStudentNumber:(NSString *)studentNumber nickName:(NSString *)nickName age:(NSUInteger)age
{
self = [super init];
if (self) {
_studentNumber = studentNumber;
_nickName = nickName;
_age = age;
}
return self;
}
-(void)study
{
NSLog(@"%@",NSStringFromSelector(__func__));
}
-(void)goSchool
{
NSLog(@"%@",NSStringFromSelector(__func__));
}
+(BOOL)accessInstanceVariablesDirectly
{
return YES;
}
Student *stu = [[Student alloc] initWithStudentNumber:@"011" nickName:@"郭德綱" age:12];
[stu study];
[stu goSchool];
NSLog(@"改變前readonly的值:%@",stu.nickName);
// stu.nickName = @"孟非";
[stu setValue:@"孟非" forKey:NSStringFromSelector(@selector(nickName))];
[stu setValue:@(21) forKey:NSStringFromSelector(@selector(age))];
NSLog(@"改變后readonly的值:%@,%ld",stu.nickName,stu.age);
為了避免KVC修改屬性值厚宰,須將定義屬性所在的類重寫方法+(BOOL)accessInstanceVariablesDirectly,使其返回NO腌巾。