iOS 魔法记录从数组导入

标签 ios core-data magicalrecord

您好,我正在制作一个同步函数,当从服务器接收到 JSON 响应时更新数据库。我希望仅在存在不同数据(新记录或更新现有记录)时才进行导入(以提高性能)(使用 coredatamagicalRecord)

这是我的 JSON 解析器方法

- (void)updateWithApiRepresentation:(NSDictionary *)json
{
    self.title = json[@"Name"];
    self.serverIdValue = [json[@"Id"] integerValue];
    self.year = json[@"Year of Release"];
    self.month = json[@"Month of Release"];
    self.day = json[@"Day of Release"];
    self.details = json[@"Description"];
    self.coverImage = json[@"CoverImage"];
    self.thumbnail = json[@"Thumbnail"];
    self.price = json[@"Buy"];

    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"dd/MMMM/yyy"];

    NSDate *date = [formatter dateFromString:[NSString stringWithFormat:@"%@/%@/%@",self.day,self.month,self.year]];
    self.issueDate = date;
}

以及我的导入方法

+ (void)API_getStampsOnCompletion:(void(^)(BOOL success, NSError     *error))completionBlock
{
    [[ApiClient sharedInstance] getStampsOnSuccess:^(id responseJSON) {

    NSManagedObjectContext *localContext = [NSManagedObjectContext MR_context];
    NSMutableArray *stamps = [[NSMutableArray alloc]init];
    [responseJSON[@"root"] enumerateObjectsUsingBlock:^(id attributes, NSUInteger idx, BOOL *stop) {
        Stamp *stamp = [[Stamp alloc]init];
        [stamp setOrderingValue:idx];
        [stamp updateWithApiRepresentation:attributes];
        [stamps addObject:stamp];
    }];

    [Stamp MR_importFromArray:stamps inContext:localContext];

} onFailure:^(NSError *error) {
        if (completionBlock) {
            completionBlock(NO, error);
        }
    }];
}

我收到错误

CoreData: error: Failed to call designated initializer on NSManagedObject class 'Stamp' 
2016-08-02 23:52:20.216 SingPost[2078:80114] -[Stamp setOrdering:]: unrecognized selector sent to instance 0x78f35a30

我检查过我的 Json 解析器工作正常。问题出在我的导入方法上。我不知道这个功能有什么问题。非常感谢任何帮助。谢谢!

最佳答案

错误消息清楚地描述了确切的问题。你这样做:

Stamp *stamp = [[Stamp alloc]init];

但是 init 不是 NSManagedObject 的指定初始化程序,除非您在子类中添加了 init(您没有提到这样做)。您必须调用指定的初始化程序,即 initWithEntity:insertIntoManagedObjectContext:NSEntityDescription 上还有一个名为 insertNewObjectForEntityForName:inManagedObjectContext: 的便捷工厂方法。这些都可以,但调用 init 不会。

关于iOS 魔法记录从数组导入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38725256/

相关文章:

ios - 如何获取 ScrollView 的contentOffset?

ios - 核心数据 - 尝试预取所有行的属性很慢

ios - MagicalRecord - 保存后数据错误

ios - NSFetchedResultsController 使用错误的更新类型进行更新

iOS: "Constants.h"错误

ios - ILTableViewCell/UITableViewCell 生命周期

objective-c - NSManagedObject 的 transient 实例

core-data - 魔法记录迁移失败 "Can' 找不到源存储的模型”

ios - 从设备中删除应用程序后,自动续订订阅会发生什么情况?

ios - 属性从 String 到 Integer 16 的核心数据迁移