一般情況下榨乎,readonly屬性的值是無法修改的鲤氢,但可以通過特殊方式修改茴她。修改本類readonly屬性的值或者子類修改父類readonly屬性的值,都可通過????方法實(shí)現(xiàn):
方法一:使用@synthesize
實(shí)現(xiàn)
在.m文件中加上@synthesize 屬性名=_屬性名
; 就可以把屬性的readonly改成readwrite了档叔。
#import "ZWViewController.h"
@interface ZWViewController ()
@property (nonatomic, copy, readonly) NSString *name;
@end
@implementation ZWViewController
@synthesize name = _name;
- (void)viewDidLoad {
[super viewDidLoad];
_name = @"zwing";
NSLog(@"%p --- %@", _name, _name);
self->_name = @"Mr_Din";
NSLog(@"%p --- %@", _name, _name);
}
2022-10-28 11:40:32.260188+0800 Go-Goal[6172:2987594] 0x104e525f8 --- zwing
2022-10-28 11:40:32.260436+0800 Go-Goal[6172:2987594] 0x104e52638 --- Mr_Din
方法二:使用kvc
實(shí)現(xiàn)
#import "ZWViewController.h"
@interface ZWViewController ()
@property (nonatomic, copy, readonly) NSString *name;
@end
@implementation ZWViewController
- (void)viewDidLoad {
[super viewDidLoad];
_name = @"zwing";
NSLog(@"%p --- %@", _name, _name);
[self setValue:@"Mr_Din" forKey:NSStringFromSelector(@selector(name))];
NSLog(@"%p --- %@", _name, _name);
}
2022-10-28 11:44:45.911732+0800 Go-Goal[6186:2989794] 0x1069525f8 --- zwing
2022-10-28 11:44:45.912061+0800 Go-Goal[6186:2989794] 0x106952638 --- Mr_Din
若想禁止kvc修改readonly屬性的值,則可以在定義readonly屬性的類中添加該方法
+ (BOOL)accessInstanceVariablesDirectly {
return NO;
}