Skip to content

Instantly share code, notes, and snippets.

@khanlou
Last active August 29, 2015 14:01
Show Gist options
  • Save khanlou/170cb132c90c86f68e72 to your computer and use it in GitHub Desktop.
Save khanlou/170cb132c90c86f68e72 to your computer and use it in GitHub Desktop.
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
Copy link

jamieQ 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