Last active
August 29, 2015 14:01
-
-
Save khanlou/170cb132c90c86f68e72 to your computer and use it in GitHub Desktop.
SKValueObject
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 anNSMutableString
instance to the initializer -- SinceNSCopying
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.