MagicalRecord导入仅保存最后一项

时间:2013-09-09 16:01:22

标签: ios objective-c afnetworking magicalrecord

我有一个AFNetworking调用,它调用我的API并存储结果。我有一个类似的电话,这种方式工作正常。但是对于这个,似乎只存储了最后一个项目。

[client getPath:@"GetItemsByFilter/" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"Operation: %@", operation);
        NSLog(@"Response: %@", responseObject);

        NSArray *customerFieldResults = [responseObject valueForKeyPath:@"details.items"];
        NSLog(@"Results: %@", customerFieldResults);
        __block NSArray *array;
        @try {
            [CustomerFields MR_truncateAll];
            array = [CustomerFields MR_importFromArray:customerFieldResults];
            NSLog(@"done setting array: %@", array);


        } @catch (NSException *e) {
            NSLog(@"Exception: %@", e);
        } @finally {
            NSLog(@"tc done");

        }
        NSLog(@"Array 1: %@", array);
        [[NSNotificationCenter defaultCenter] postNotificationName:kCustomerFieldSetComplete object:nil];

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Operation: %@", operation);
        NSError *jsonError;
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:[[error localizedRecoverySuggestion] dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&jsonError];
        NSLog(@"Error: %@", [error localizedRecoverySuggestion]);

        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@"Api Error: %@", [dict valueForKey:@"status"]] message:[dict valueForKey:@"statusMessage"] delegate:nil cancelButtonTitle:NSLocalizedString(@"Ok", @"Okay button") otherButtonTitles:nil];

        [alert show];
    }];

当我使用上下文时,它甚至不保存项目。我在收到此信息时发送通知,并在该通知中显示[CustomerFields findAll]的结果。只有[CustomerFields findAll]找到一个项目。

Array1显示了完整的项目列表,但是一旦我回到另一个控制器,它只返回数组中最后一个项目。此外,如果我将其包裹在saveWithBlock中,它将看不到另一个控制器中的任何项目。

为什么在我执行findAll时只显示导入的最后一条记录?

2 个答案:

答案 0 :(得分:0)

我对Magical Record不太熟悉,但也许你没有保存你的核心数据上下文?

我假设方法MR_importFromArray:将记录插入CoreData?

如果情况并非如此,您可能希望循环搜索结果并逐个创建它们?

[client getPath:@"GetItemsByFilter/" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject)
{
    NSArray *customerFieldResults = [responseObject valueForKeyPath:@"details.items"];

    customerFieldResults = [CustomerFields MR_importFromArray:customerFieldResults];

    //loop through array and create records

    //save your core data context here

    [[NSNotificationCenter defaultCenter] postNotificationName:kCustomerFieldSetComplete object:nil];
}
failure:^(AFHTTPRequestOperation *operation, NSError *error){}];

答案 1 :(得分:0)

我明白了。事实证明我正在使用的API已更改,而我正在使用的字段relatedByAttribute空白(一个错误),所以它认为我的所有记录都是重复的并覆盖它们。