Search code examples
iosobjective-cdesign-patternsmutablesubclassing

Objective-C Mutable subclass pattern?


Is there a standard pattern for implementing a mutable/immutable object class pair in Objective-C? I currently have something like the following, which I wrote based off this link

Immutable Class:

@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

Mutable Class:

@interface MyMutableObject : MyObject
@property (nonatomic, readwrite, strong) NSString *value;
@end


@implementation MyMutableObject
@dynamic value;

- (void)setValue:(NSString *)value {
    _value = value;
}

@end

This works, but it exposes the iVar. Is there a better implementation that remedies this situation?


Solution

  • Your solution follows a very good pattern: the mutable class does not duplicate anything from its base, and exposes an additional functionality without storing any additional state.

    This works, but it exposes the iVar.

    Due to the fact that instance variables are @protected by default, the exposed _value is visible only to the classes inheriting MyObject. This is a good tradeoff, because it helps you avoid data duplication without publicly exposing the data member used for storing the state of the object.