Skip to content

Instantly share code, notes, and snippets.

@Mozilla9
Last active August 5, 2020 23:22
Show Gist options
  • Save Mozilla9/c8d62f5cf0fffa81300c to your computer and use it in GitHub Desktop.
Save Mozilla9/c8d62f5cf0fffa81300c to your computer and use it in GitHub Desktop.
JSONModel + MagicalRecord

Create CoreData entity from JSONModel object

#import "JSONModel.h"

@interface User : JSONModel

@property(nonatomic, copy) NSString <Optional> *name;
@property(nonatomic, copy) NSString <Optional> *email;
@property(nonatomic, copy) NSString <Optional> *phone;
@property(nonatomic, copy) NSString <Optional> *password;

- (NSManagedObject *)createCoreDataModel:(NSManagedObjectContext *)context;

@end
#import "CDUser.h"
#import "NSManagedObject+MagicalDataImport.h"

@implementation User

- (Class)relatedCoreDataModelClass
{
    return [CDUser class];
}

- (NSManagedObject *)createCoreDataModel:(NSManagedObjectContext *)context
{
    return [[self relatedCoreDataModelClass] MR_importFromObject:[self toDictionary] inContext:context];
}

Create JSONModel object from CoreData entity

#import "User.h"

#import "NSManagedObject+JsonSerialization.h" // see https://github.com/Mozilla9/coredata-to-json
#import "NSManagedObject+MagicalFinders.h"

@implementation UserManager

- (User *)loadUserWithPredicate:(NSPredicate *)predicate inContext:(NSManagedContext *)context
{
    CDUser *cdUser = [CDUser MR_findFirstWithPredicate:predicate inContext:context];
    
    NSDictionary *dict = [cdUser toDictionary];
    NSError *error = nil;
    
    User *user = [User initWithDictionary:dict error:&error];

    return user;
}

@end

Notes

  1. Link to the lib https://github.com/Mozilla9/coredata-to-json

  2. notSerializeToJSON key for relationship.

It allows to break a relationship cycle. E.g. CDUser has an inverse relantionship to entity CDJob. So when we convert CDUser to NSDictionary, it performs converting of CDJob too. But CDJob has a relationship to CDUser and it spawns an infinite cycle.

Example how use it. not_serialize_to_json

  1. kMagicalRecordImportAttributeKeyMapKey key for CD attributes.

Similar to the JSONKeyMapper.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment