Skip to content
This repository was archived by the owner on Sep 12, 2018. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
85 changes: 38 additions & 47 deletions Classes/NSManagedObject+ActiveRecord.m
Original file line number Diff line number Diff line change
Expand Up @@ -64,8 +64,10 @@ + (instancetype)findOrCreate:(NSDictionary *)properties {
}

+ (instancetype)findOrCreate:(NSDictionary *)properties inContext:(NSManagedObjectContext *)context {
NSManagedObject *existing = [self where:properties inContext:context].first;
return existing ?: [self create:properties inContext:context];
NSDictionary *transformed = [[self class] transformProperties:properties withContext:context];

NSManagedObject *existing = [self where:transformed inContext:context].first;
return existing ?: [self create:transformed inContext:context];
}

+ (instancetype)find:(id)condition, ... {
Expand Down Expand Up @@ -170,16 +172,13 @@ + (id)createInContext:(NSManagedObjectContext *)context {
- (void)update:(NSDictionary *)attributes {
unless([attributes exists]) return;

for (id key in attributes) [self willChangeValueForKey:key];
[attributes each:^(id key, id value) {
id remoteKey = [self.class keyForRemoteKey:key];
NSDictionary *transformed = [[self class] transformProperties:attributes withContext:self.managedObjectContext];

if ([remoteKey isKindOfClass:[NSString class]])
[self setSafeValue:value forKey:remoteKey];
else
[self hydrateObject:value ofClass:remoteKey[@"class"] forKey:remoteKey[@"key"] ?: key];
for (NSString *key in transformed) [self willChangeValueForKey:key];
[transformed each:^(NSString *key, id value) {
[self setSafeValue:value forKey:key];
}];
for (id key in attributes) [self didChangeValueForKey:key];
for (NSString *key in transformed) [self didChangeValueForKey:key];
}

- (BOOL)save {
Expand All @@ -203,27 +202,47 @@ + (void)deleteAllInContext:(NSManagedObjectContext *)context {
#pragma mark - Naming

+ (NSString *)entityName {

return NSStringFromClass(self);
}

#pragma mark - Private

+ (NSDictionary *)transformProperties:(NSDictionary *)properties withContext:(NSManagedObjectContext *)context {
NSEntityDescription *entity = [NSEntityDescription entityForName:[self entityName] inManagedObjectContext:context];

NSDictionary *attributes = [entity attributesByName];
NSDictionary *relationships = [entity relationshipsByName];

NSMutableDictionary *transformed = [NSMutableDictionary dictionaryWithCapacity:[properties count]];

for (NSString *key in properties) {
NSString *localKey = [self keyForRemoteKey:key inContext:context];
if (attributes[localKey] || relationships[localKey]) {
transformed[localKey] = [[self class] transformValue:properties[key] forRemoteKey:key inContext:context];
} else {
#if DEBUG
NSLog(@"Discarding key ('%@') from properties on class ('%@'): no attribute or relationship found",
key, [self class]);
#endif
}
}

return transformed;
}

+ (NSPredicate *)predicateFromDictionary:(NSDictionary *)dict {
NSArray *subpredicates = [dict map:^(id key, id value) {
return [NSPredicate predicateWithFormat:@"%K == %@", [self keyForRemoteKey:key], value];
NSArray *subpredicates = [dict map:^(NSString *key, id value) {
return [NSPredicate predicateWithFormat:@"%K = %@", key, value];
}];

return [NSCompoundPredicate andPredicateWithSubpredicates:subpredicates];
}

+ (NSPredicate *)predicateFromObject:(id)condition
{
+ (NSPredicate *)predicateFromObject:(id)condition {
return [self predicateFromObject:condition arguments:NULL];
}

+ (NSPredicate *)predicateFromObject:(id)condition arguments:(va_list)arguments
{
+ (NSPredicate *)predicateFromObject:(id)condition arguments:(va_list)arguments {
if ([condition isKindOfClass:[NSPredicate class]])
return condition;

Expand Down Expand Up @@ -314,41 +333,13 @@ - (BOOL)saveTheContext {
return YES;
}

- (void)hydrateObject:(id)properties ofClass:(Class)class forKey:(NSString *)key {
[self setSafeValue:[self objectOrSetOfObjectsFromValue:properties ofClass:class]
forKey:key];
}

- (id)objectOrSetOfObjectsFromValue:(id)value ofClass:(Class)class {
if ([value isKindOfClass:class])
return value;

if ([value isKindOfClass:[NSDictionary class]])
return [class findOrCreate:value inContext:self.managedObjectContext];

if ([value isKindOfClass:[NSArray class]])
return [NSSet setWithArray:[value map:^id(id object) {
return [self objectOrSetOfObjectsFromValue:object ofClass:class];
}]];

return [class findOrCreate:@{ [class primaryKey]: value } inContext:self.managedObjectContext];
}

- (void)setSafeValue:(id)value forKey:(id)key {
NSAttributeDescription *attribute = [[self entity] attributesByName][key];

if (attribute == nil && [[self entity] relationshipsByName][key] == nil) {
#if DEBUG
NSLog(@"Could not set value ('%@') for key ('%@') on class ('%@'): No attribute or relationship found", value, key, NSStringFromClass([self class]));
#endif
return;
}

- (void)setSafeValue:(id)value forKey:(NSString *)key {
if (value == nil || value == [NSNull null]) {
[self setNilValueForKey:key];
return;
}

NSAttributeDescription *attribute = [[self entity] attributesByName][key];
NSAttributeType attributeType = [attribute attributeType];

if ((attributeType == NSStringAttributeType) && ([value isKindOfClass:[NSNumber class]]))
Expand Down
18 changes: 15 additions & 3 deletions Classes/NSManagedObject+Mappings.h
Original file line number Diff line number Diff line change
Expand Up @@ -36,17 +36,29 @@

@see +[NSManagedObject mappings]

@param key A remote (server) attribute name.
@param key A remote (server) attribute name.
@param context A local managed object context.

@return A local (Core Data) attribute name.
*/
+ (id)keyForRemoteKey:(NSString *)key;
+ (NSString *)keyForRemoteKey:(NSString *)remoteKey inContext:(NSManagedObjectContext *)context;

/**
Transforms a given object for a remote attribute name.

@param value Object to be transformed (e.g., a dictionary may become a managed object)
@param remoteKey A remote (server) attribute name.
@param context A local managed object context.

@return A tranformed object.
*/
+ (id)transformValue:(id)value forRemoteKey:(NSString *)remoteKey inContext:(NSManagedObjectContext *)context;

/**
The keypath uniquely identifying your entity. Usually an ID, e.g., @c @@"remoteID".

@return An attribute name.
*/
+ (id)primaryKey;
+ (NSString *)primaryKey;

@end
79 changes: 57 additions & 22 deletions Classes/NSManagedObject+Mappings.m
Original file line number Diff line number Diff line change
Expand Up @@ -24,50 +24,84 @@
#import "NSManagedObject+ActiveRecord.h"
#import "ObjectiveSugar.h"


@implementation NSManagedObject (Mappings)

+ (id)keyForRemoteKey:(NSString *)remoteKey {

if (self.cachedMappings[remoteKey])
return self.cachedMappings[remoteKey];
+ (NSString *)keyForRemoteKey:(NSString *)remoteKey inContext:(NSManagedObjectContext *)context {
if ([self cachedMappings][remoteKey])
return [self cachedMappings][remoteKey][@"key"];

NSString *camelCasedProperty = [remoteKey.camelCase stringByReplacingCharactersInRange:NSMakeRange(0, 1)
withString:[[remoteKey substringWithRange:NSMakeRange(0, 1)] lowercaseString]];
NSString *camelCasedProperty = [[remoteKey camelCase] stringByReplacingCharactersInRange:NSMakeRange(0, 1)
withString:[[remoteKey substringWithRange:NSMakeRange(0, 1)] lowercaseString]];

NSEntityDescription *desc = [NSEntityDescription entityForName:[self entityName] inManagedObjectContext:[NSManagedObjectContext defaultContext]];
NSEntityDescription *entity = [NSEntityDescription entityForName:[self entityName]
inManagedObjectContext:context];

if ([desc propertiesByName][camelCasedProperty]) {
self.cachedMappings[remoteKey] = camelCasedProperty;
if ([entity propertiesByName][camelCasedProperty]) {
[self cacheKey:camelCasedProperty forRemoteKey:camelCasedProperty];
return camelCasedProperty;
}

[self cachedMappings][remoteKey] = remoteKey;
[self cacheKey:remoteKey forRemoteKey:remoteKey];
return remoteKey;
}

+ (id)transformValue:(id)value forRemoteKey:(NSString *)remoteKey inContext:(NSManagedObjectContext *)context {
Class class = [self cachedMappings][remoteKey][@"class"];
if (class)
return [self objectOrSetOfObjectsFromValue:value ofClass:class inContext:context];

return value;
}

#pragma mark - Private

+ (NSMutableDictionary *)cachedMappings {
NSMutableDictionary *mappingsForClass = [NSManagedObject sharedMappings][self.class];
+ (id)objectOrSetOfObjectsFromValue:(id)value ofClass:class inContext:(NSManagedObjectContext *)context {
if ([value isKindOfClass:class])
return value;

if (!mappingsForClass) {
mappingsForClass = [self mappings].mutableCopy ?: @{}.mutableCopy;
[NSManagedObject sharedMappings][(id<NSCopying>)self.class] = mappingsForClass;
}
if ([value isKindOfClass:[NSDictionary class]])
return [class findOrCreate:value inContext:context];

return mappingsForClass;
if ([value isKindOfClass:[NSArray class]])
return [NSSet setWithArray:[value map:^id(id object) {
return [self objectOrSetOfObjectsFromValue:object ofClass:class inContext:context];
}]];

return [class findOrCreate:@{ [class primaryKey]: value } inContext:context];
}

+ (NSMutableDictionary *)cachedMappings {
NSMutableDictionary *cachedMappings = [self sharedMappings][[self class]];
if (!cachedMappings) {
cachedMappings = [self sharedMappings][(id<NSCopying>)[self class]] = [NSMutableDictionary new];

[[self mappings] each:^(id key, id value) {
if ([value isKindOfClass:[NSString class]])
[self cacheKey:value forRemoteKey:key];

else {
cachedMappings[key] = value;
[self cacheKey:key forRemoteKey:key];
}
}];
}
return cachedMappings;
}

+ (NSMutableDictionary *)sharedMappings {
static NSMutableDictionary *singleton;
static NSMutableDictionary *sharedMappings;
static dispatch_once_t singletonToken;
dispatch_once(&singletonToken, ^{
singleton = @{}.mutableCopy;
sharedMappings = [NSMutableDictionary new];
});
return singleton;
return sharedMappings;
}

+ (void)cacheKey:(NSString *)key forRemoteKey:(NSString *)remoteKey {
NSMutableDictionary *mapping = [[self cachedMappings][remoteKey] mutableCopy] ?: [NSMutableDictionary new];
if (mapping[@"key"] == nil) mapping[@"key"] = key;
[self cachedMappings][remoteKey] = mapping;
}

#pragma mark - Abstract

Expand All @@ -77,7 +111,8 @@ + (NSDictionary *)mappings {

+ (id)primaryKey {
@throw [NSException exceptionWithName:NSStringWithFormat(@"Primary key undefined in %@", self.class)
reason:NSStringWithFormat(@"You need to override %@ +primaryKey if you want to support automatic creation with only object ID", self.class)
reason:NSStringWithFormat(@"You need to override %@ +primaryKey if you want to support automatic creation with only object ID",
self.class)
userInfo:nil];
}

Expand Down
7 changes: 7 additions & 0 deletions Example/SampleProjectTests/MappingsTests.m
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,13 @@
[[car shouldNot] receive:@selector(setPrimitiveValue:forKey:)];
[car update:@{ @"chocolate": @"waffles" }];
});

it(@"ignores embedded unknown keys", ^{
[[theBlock(^{
Car *car = [Car create];
[car update:@{ @"owner": @{ @"coolness": @(100) } }];
}) shouldNot] raise];
});
});

SPEC_END