Skip to content

Instantly share code, notes, and snippets.

@khanlou khanlou/SKValueObject.h
Last active Aug 29, 2015

Embed
What would you like to do?
SKValueObject
//
// SKValueObject.h
// TinyType
//
// Created by Soroush Khanlou on 5/15/14.
// Copyright (c) 2014 Soroush Khanlou. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface SKValueObject : NSObject <NSCopying>
- (instancetype)initWithBackingObject:(id)backingObject;
@property (nonatomic, readonly) id backingObject;
@end
//
// SKValueObject.m
// TinyType
//
// Created by Soroush Khanlou on 5/15/14.
// Copyright (c) 2014 Soroush Khanlou. All rights reserved.
//
#import "SKValueObject.h"
@interface SKValueObject ()
@property (nonatomic, strong) id backingObject;
@end
@implementation SKValueObject
- (instancetype)initWithBackingObject:(id)backingObject {
self = [super init];
if (!self) return nil;
_backingObject = backingObject;
return self;
}
- (BOOL)isEqual:(id)other {
if (other == self) return YES;
if (![other isKindOfClass:self.class]) return NO;
return [self isEqualToValueObject:other];
}
- (BOOL)isEqualToValueObject:(SKValueObject*)otherValueObject {
return [self.backingObject isEqual:otherValueObject.backingObject];
}
- (NSString *)description {
return [NSString stringWithFormat:@"<%p: %@> {Value: %@}", self, self.class, self.backingObject];
}
- (NSComparisonResult)compare:(SKValueObject*)otherValueObject {
return [self.backingObject compare:otherValueObject.backingObject];
}
- (NSUInteger)hash {
return [self.backingObject hash];
}
- (id)copyWithZone:(NSZone *)zone {
return [[self.class allocWithZone:zone] initWithBackingObject:self.backingObject];
}
@end
@jamieQ

This comment has been minimized.

Copy link

commented Aug 22, 2015

Hi! Fan of the blog. One thing I wanted to note was that this implementation does have a possible issue if initialized with a backingObject that has a mutable subclass. The standard example being where you pass in an NSMutableString instance to the initializer -- Since NSCopying isn't enforced on that parameter, we can't copy it on initialization, and therefore it could mutate without the value object wrapper being aware.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.