【问题标题】:iOS Magical record import from arrayiOS从数组导入神奇记录
【发布时间】:2016-12-08 02:13:33
【问题描述】:

您好,我正在制作一个同步功能,当收到来自服务器的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 解析器工作正常。问题出在我的导入方法上。我不知道这个功能有什么问题。非常感谢任何帮助。谢谢!

【问题讨论】:

    标签: ios core-data magicalrecord


    【解决方案1】:

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

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

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

    【讨论】:

    • 您好,感谢您的帮助,我正在使用 Magical Record 库。以上是否等于 Stamp *stamp = [Stamp MR_createEntityInContext:localContext];?添加新记录时有什么方法可以避免重复?
    • 我没用过Magical Record所以不能确定。
    • 那么你知道如何避免添加重复记录(从服务器接收到json响应后)吗?
    • 您可以进行提取以查看是否已经存在任何匹配的记录,也可以在数据模型中使用唯一约束(在 WWDC 2015 中进行了描述)。或者 Magical Record 可能会对此有所帮助。
    • 无论如何我们可以在添加新实体之前创建实体数组吗(比如执行批量添加)?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多