在Objective-C中是否有用于实现可变/不可变对象类对的标准模式?我目前有类似以下内容,我根据此链接编写
不可变类:
@interface MyObject : NSObject <NSMutableCopying> {
NSString *_value;
}
@property (nonatomic, readonly, strong) NSString *value;
- (instancetype)initWithValue:(NSString *)value;
@end
@implementation MyObject
@synthesize value = _value;
- (instancetype)initWithValue:(NSString *)value {
self = [self init];
if (self) {
_value = value;
}
return self;
}
- (id)mutableCopyWithZone:(NSZone *)zone {
return [[MyMutableObject allocWithZone:zone] initWithValue:self.value];
}
@end
Run Code Online (Sandbox Code Playgroud)
可变类:
@interface MyMutableObject : MyObject
@property (nonatomic, readwrite, strong) NSString *value;
@end
@implementation MyMutableObject
@dynamic value;
- (void)setValue:(NSString *)value {
_value = value; …Run Code Online (Sandbox Code Playgroud)