使用Magical Record将对象数组插入Core Data

时间:2014-08-14 13:56:29

标签: ios core-data magicalrecord

我是一名拥有核心数据和神奇记录的新手,我在插入数据方面遇到了问题。

返回JSON的Web服务:

enter image description here

核心数据数据库:

enter image description here

enter image description here

enter image description here

enter image description here

Objective-C代码

- (void)fetchDocumentsOnCompletion:(void(^) (NSDictionary *data,NSError *error))completionBlock
{
    [self GET:@"documents" parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {

        NSArray *documentsArray = [Document MR_importFromArray:responseObject[@"documents"]];

        [MagicalRecord saveWithBlock:^(NSManagedObjectContext *localContext) {
            [Document MR_importFromArray:documentsArray inContext:localContext];
        } completion:^(BOOL success, NSError *error) {

        }];



    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        completionBlock(nil, error);
    }];

}

如果我将断点置于

之下
NSArray *documentsArray = [Document MR_importFromArray:responseObject[@"documents"]];

数组具有以下值:

enter image description here

但是当我删除断点并再次编译时,我得到了这个崩溃:

enter image description here

我没有发现错误,有人可以帮帮我吗?

2 个答案:

答案 0 :(得分:0)

尝试使用_id作为属性的名称而不是id

答案 1 :(得分:0)

要使用MagicalRecord保存和获取数据,您需要将数据保存在本地上下文中,然后询问对象的唯一ID。然后使用谓词来检索它们。

我在我的代码中使用类似的东西:

- (void)fetchDocumentsOnCompletion:(void(^) (NSArray *data, NSError *error))completionBlock
{
    [self GET:@"documents" parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {


        // Create an array that's going to save all your unique
        // newly created object ids
        // 
        NSMutableArray *objectIDs = [NSMutableArray array];

        [MagicalRecord saveWithBlock:^(NSManagedObjectContext *localContext) {

            NSArray *documentsArray = [Document MR_importFromArray :responseObject[@"documents"] inContext:localContext];


            // Obtain Permanent Id used to retrieve objects after
            // it's being saved
            //
            NSError *error;
            if ([localContext obtainPermanentIDsForObjects:documentsArray error:&error]) {
                for (NSManagedObject *obj in documentsArray) {
                    [objectIDs addObject:[obj objectID]];
                }
            }

        } completion:^(BOOL success, NSError *error) {

            // Fetch items
            //
            id newlyCreatedItemsNowInMainContext = !error ? [Document findAllWithPredicate:[NSPredicate predicateWithFormat:@"self IN %@", objectIDs]] : nil)
            if (completionBlock)
                completionBlock(newlyCreatedItemsNowInMainContext, error)
        }];

    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        completionBlock(nil, error);
    }];
}