Skip to content

Instantly share code, notes, and snippets.

@jeremyquinn
Created May 25, 2013 16:53
Show Gist options
  • Save jeremyquinn/5649781 to your computer and use it in GitHub Desktop.
Save jeremyquinn/5649781 to your computer and use it in GitHub Desktop.
This is a Category on NSManagedObject, that enables subscript access to properties.
This is a Category on NSManagedObject, that enables subscript access to properties.
I find this useful as I prefer (for several reasons) not to compile against my model entities but to access them as I would a NSDictionary, with string constants for keys.
So instead of
[myEntity valueForKey:@"title"]
you can use
myEntity[@"title"]
and instead of
[myEntity setValue:@"Hello World" forKey:@"title"]
you can use
myEntity[@"title"] = @"Hello World"
Enjoy!
//
// NSManagedObject+KeyedSubscript.h
//
// Created by Jeremy Quinn on 25/05/2013.
// Copyright (c) 2013 FiveOne.org. All rights reserved.
//
#import <CoreData/CoreData.h>
@interface NSManagedObject (KeyedSubscript)
// getter
- (id)objectForKeyedSubscript:(NSString*)key;
// setter
- (void)setObject:(id)object forKeyedSubscript:(id<NSCopying>)key;
@end
//
// NSManagedObject+KeyedSubscript.m
//
// Created by Jeremy Quinn on 25/05/2013.
// Copyright (c) 2013 FiveOne.org. All rights reserved.
//
#import "NSManagedObject+KeyedSubscript.h"
@implementation NSManagedObject (KeyedSubscript)
- (id)objectForKeyedSubscript:(NSString*)key {
return [self valueForKey:key];
}
- (void)setObject:(id)object forKeyedSubscript:(id<NSCopying>)key {
NSParameterAssert([(id<NSObject>)key isKindOfClass:[NSString class]]);
[self setValue:object forKey:(NSString*)key];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment