iOS-修改readonly属性的值
2022-10-27 本文已影响0人
zwing
一般情况下,readonly属性的值是无法修改的,但可以通过特殊方式修改。修改本类readonly属性的值或者子类修改父类readonly属性的值,都可通过👇🏻方法实现:
方法一:使用@synthesize
实现
在.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
实现
#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;
}