Skip to content

Instantly share code, notes, and snippets.

@vilhalmer
Created February 21, 2015 00:14
Show Gist options
  • Save vilhalmer/85f08dca272a6ebfad51 to your computer and use it in GitHub Desktop.
Save vilhalmer/85f08dca272a6ebfad51 to your computer and use it in GitHub Desktop.
NSCoder+KeyedSubscripting
// NSCoder+KeyedSubscripting.h:
@interface NSCoder (KeyedSubscripting)
- (id)objectForKeyedSubscript:(id <NSCopying>)key;
- (void)setObject:(id)object forKeyedSubscript:(id <NSCopying>)key;
@end
@interface NSKeyedArchiver (KeyedSubscripting)
- (void)setObject:(id)object forKeyedSubscript:(id<NSCopying>)key;
@end
@interface NSKeyedUnarchiver (KeyedSubscripting)
- (id)objectForKeyedSubscript:(id<NSCopying>)key;
@end
// NSCoder+KeyedSubscripting.m:
@implementation NSCoder (KeyedSubscripting)
- (id)objectForKeyedSubscript:(id<NSCopying>)key
{
return nil; // Handled by subclass
}
- (void)setObject:(id)object forKeyedSubscript:(id<NSCopying>)key
{
// Handled by subclass
}
@end
@implementation NSKeyedArchiver (KeyedSubscripting)
- (id)objectForKeyedSubscript:(id<NSCopying>)key
{
@throw [NSException exceptionWithName:@"USLInvalidOperationException" reason:@"Cannot retrieve object from NSKeyedArchiver using subscripting" userInfo:nil];
}
- (void)setObject:(id)object forKeyedSubscript:(id<NSCopying>)key
{
[self encodeObject:object forKey:(NSString *)key];
}
@end
@implementation NSKeyedUnarchiver (KeyedSubscripting)
- (id)objectForKeyedSubscript:(id<NSCopying>)key
{
return [self decodeObjectForKey:(NSString *)key];
}
- (void)setObject:(id)object forKeyedSubscript:(id<NSCopying>)key
{
@throw [NSException exceptionWithName:@"USLInvalidOperationException" reason:@"Cannot store object in NSKeyedUnarchiver using subscripting" userInfo:nil];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment