dchohfi / KeyValueObjectMapping

Automatic KeyValue Object Mapping for Objective-C, parse JSON/plist/Dictionary automatically
http://dchohfi.com/
MIT License
602 stars 90 forks source link

CoreData Sample Code #51

Open expkzb opened 10 years ago

expkzb commented 10 years ago

Hi dchohfi, I really don't know how to deal with core data object mapping using DCCustomInitialize. Could you please write a few sample codes for me? THX : )

pronebird commented 8 years ago

I don't understand how to use it with CoreData either.

R3inhardH commented 8 years ago

Hi, I had to deal with CoreData a few days ago and found out that you have to use a DCCustomInitialize object. Here is a short example that should give the idea how to do this:

If you have a dictionary which looks like this:

{
    "user_name": "John",
    "age_integer": 23 
}

and the according classes:

User.h

#import <CoreData/CoreData.h>
NS_ASSUME_NONNULL_BEGIN
@interface User : NSManagedObject

@end
NS_ASSUME_NONNULL_END

#import "User+CoreDataProperties.h"

User+CoreDataProperties.h

NS_ASSUME_NONNULL_BEGIN

@interface VFBConfigPackage (CoreDataProperties)

@property (nullable, nonatomic, retain) NSString *userName;
@property (nullable, nonatomic, retain) NSNumber *userAge;

@end

NS_ASSUME_NONNULL_END

ViewController.h

- (void)viewDidLoad {
[super viewDidLoad];

    NSDictionary *json = //see example

    DCCustomInitialize *initializer = [[DCCustomInitialize alloc] initWithBlockInitialize:^id(__weak Class classOfObjectToGenerate, NSDictionary *__weak values, __weak id parentObject) {
        User *managedObject = (User *)[NSEntityDescription insertNewObjectForEntityForName:@"User"
                                         inManagedObjectContext:managedObjectContext];
        return managedObject;
    } forClass:[User class]];

    DCParserConfiguration *config = [DCParserConfiguration configuration];
    [config addCustomInitializersObject:initializer];
    [config addObjectMapping:[DCObjectMapping mapKeyPath:@"user_name" toAttribute:@"userName" onClass:[User class]]];
    [config addObjectMapping:[DCObjectMapping mapKeyPath:@"age_integer" toAttribute:@"userAge" onClass:[User class]]];

    DCKeyValueObjectMapping *parser = [DCKeyValueObjectMapping mapperForClass:[User class] andConfiguration:config];
    User *user = [parser parseDictionary:jsonDict];

    //Continue with the User Object
}

Hope this helps