簡體   English   中英

如何在iOS的核心數據中存儲JSON數據

[英]How to Store JSON Data in Core Data in iOS

我正在從JSON中獲取響應,該響應存儲在數組中,我想將{albumId albumName coverPhotoURL createdDate}的值存儲在Core Data中,請幫助我。

    (
        {
        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;
       }
   )

您需要創建NSManagedObject的子類並定義所有需要的字段

@interface AlbumInfo : NSManagedObject

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

@end

那么您需要調用此代碼

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]);
    }
} 
  • 我假設您創建了一個適合您需要存儲的數據的實體。
  • 然后創建NSEntityDescriptionNSManagedObject開始將您的對象加載到Core Data

     NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"ALbum" inManagedObjectContext:self.managedObjectContext]; NSManagedObject *newAlbum = [[NSManagedObject alloc] initWithEntity:entityDescription insertIntoManagedObjectContext:self.managedObjectContext]; 
  • 然后您應該將值設置為托管對象

     [newPerson setValue:@"photos took in Dubai" forKey:@"description"]; [newPerson setValue:@" UAE" forKey:@"albumName"]; 
  • 最后一步,您應該保存這些更改,如下所示

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

我想建議使用MagicalRecord導入數據,這是CoreData的出色包裝。 它提供了有關數據導入配置方法的約定。

導入功能能夠映射數據,即使您的json模型中的屬性與實體相比有所不同,或者您想將字符串中表示的日期轉換為NSDate

為了避免重復輸入,MagicalRecord約定使用唯一ID。 即,它期望實體相冊的唯一ID屬性,例如AlbumID,Employee-employeeID等。因此,需要按照慣例對其進行建模。 根據您的案例模型將是這樣。

在此處輸入圖片說明

您可以注意到,在albumID的用戶信息中,該屬性已映射到AlbumId。 類似地, createdDate不是保存字符串值,而是NSDate

在此處輸入圖片說明

dateFormat設置為createdDate的UserInfo

至此,配置部分完成。 您可以將日期導入到CoreData中,如下所示:

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

使用以下命令檢查數據是否正確導入

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM