简体   繁体   中英

How to Store JSON Data in Core Data in iOS

I am getting the response from JSON is stored in an array and I want to store the values {albumId albumName coverPhotoURL createdDate} in Core Data please help me.

    (
        {
        albumId = 1;
        albumName = UAE;
        coverPhotoURL = "http://1-dot-digiphoto-01.appspot.com/serve?blob-key=AMIfv95XeG-ii4aKZsUB5w-ClP0QUhJZa-o5BQRvdqArCCwg0Ueb13-wAfmyNHgaDdTaFS152_kXkJg5_9386zlfRCDc3fagW7Ekagdd6_VvJl6IscqNkyvVkXKYAqIRe-KqDMpjG-cW";
        createdDate = "10-Jun-2010 06:11 PM";
        description = "photos took in Dubai";
        lastViewedDate = "10-Jun-2010 06:11 PM";
        modifiedDate = "10-Jun-2010 06:11 PM";
        numberOfPhotos = 10;
       }
   )

You need to create a subclass of NSManagedObject and define all needed fields

@interface AlbumInfo : NSManagedObject

@property (nonatomic, retain) NSNumber * albumId;
@property (nonatomic, retain) NSString * albumName;
@property (nonatomic, retain) NSString * coverPhotoURL;
@property (nonatomic, retain) NSDate * createdDate;

@end

then you need to call this code

context = /* Get the NSManagedObject context */

AlbumInfo *item = [NSEntityDescription insertNewObjectForEntityForName:@"AlbumInfo" inManagedObjectContext:context];

item.albumId = @"some value from json";
/* ... so on ...*/

NSError *error = nil;
if (context != nil) {
    if ([managedObjectContext hasChanges] && ![context save:&error]) {
        // Replace this implementation with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
    }
} 
  • I Suppose you created an Entity That fits the data you need to store.
  • Then Create NSEntityDescription and NSManagedObject to start load your object into Core Data .

     NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"ALbum" inManagedObjectContext:self.managedObjectContext]; NSManagedObject *newAlbum = [[NSManagedObject alloc] initWithEntity:entityDescription insertIntoManagedObjectContext:self.managedObjectContext]; 
  • Then you should set values into managed object

     [newPerson setValue:@"photos took in Dubai" forKey:@"description"]; [newPerson setValue:@" UAE" forKey:@"albumName"]; 
  • Last Step you should save These changes like this

     NSError *error = nil; if (![newAlbum.managedObjectContext save:&error]) { NSLog(@"Unable to save managed object context."); NSLog(@"%@, %@", error, error.localizedDescription); } 

I would like to suggest importing data using MagicalRecord an excellent wrapper for CoreData. It provides convention over configuration method of data import.

The importing feature is capable of mapping the data even if the properties are different in your json model compared to entity or if you would like to convert date represented in string to NSDate

To avoid duplicate entries, MagicalRecord makes it a convention to use a uniqueID. ie, It expects a uniqueID property for an entity Album like albumID, Employee - employeeID etc. So one need to model it as per convention. As per your case model would be like this.

在此处输入图片说明

You can note that in the User Info of albumID , the property is mapped to albumId. Similarly the createdDate is not holding a string value but a NSDate .

在此处输入图片说明

A dateFormat is set to the UserInfo of createdDate

Now the configuration part is completed. You can import the date to CoreData as in

NSData *jsonData = //Data from web service;
NSArray *albums = [NSJSONSerialization JSONObjectWithData:jsonData
                                                  options:0
                                                    error:nil];
for (id obj in albums) {
    [Album MR_importFromObject:obj];
}

Check if data is properly imported using

NSArray *savedAlbums = [Album MR_findAll];
Album *album = [savedAlbums lastObject];
NSLog(@"Created Date : %@",album.createdDate);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM