核心数据 - 放弃更改 [英] Core Data - Discard changes

查看:166
本文介绍了核心数据 - 放弃更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

希望有人能解释发生了什么。

Hope someone can explain what's going on.

如果我从我的Core Data模型中获取一个对象,修改一个没有持久化甚至在模型中定义的属性!

If I get an object from my Core Data model, modify a property which is not persisted or even defined in the model! and then destroy and get the object again the value is still as previously set.

为什么是这样?

Promotion *promotion = [Promotion promotionWithId:[NSNumber numberWithInt:1512] inManagedObjectContext:context];
    [promotion setQuantity:[NSNumber numberWithInt:2]];
    NSLog(@"%d", [promotion.quantity intValue]);
    promotion = nil;

    promotion = [Promotion promotionWithId:[NSNumber numberWithInt:1512] inManagedObjectContext:context];
    NSLog(@"%d", [promotion.quantity intValue]);
    promotion = nil;

输出为:

2
2

2 2

参考资料:

+(Promotion *)promotionWithId:(NSNumber *)promotionId inManagedObjectContext:(NSManagedObjectContext *) context {
    NSFetchRequest *fetchReq = [[NSFetchRequest alloc]init];
    [fetchReq setEntity:[NSEntityDescription entityForName:@"Promotion" inManagedObjectContext:context]];

    NSPredicate *query = [NSPredicate predicateWithFormat:@"promotionId=%d", [promotionId intValue]];
    [fetchReq setPredicate:query];

    NSMutableArray *resultArray = [[NSMutableArray alloc]initWithArray:[context executeFetchRequest:fetchReq error:nil]];

    if([resultArray count] > 0) {
        return [resultArray objectAtIndex:0];
    }

    return nil;
}


推荐答案

你使所有被管理的对象保存在Coredata的被管对象上下文,直到你坚持它们(即保存上下文)。

Keep in mind that the changes you make to all managed objects are kept on Coredata's managed object context until you persist them (i.e. save the context).

在你的情况下,管理对象,将其引用设置为nil,但不会重置上下文。

So in your case, you are making a change to the managed object, setting it's reference to nil but not resetting the context.

这意味着您的更改仍然有效,下次您提取相同的对象时,它将被应用。

This means your change is still valid and the next time you fetch the same object it will be applied.

为了完全摆脱它,你需要重置上下文:

To get rid of it completely, you will need to reset the context with:

[context reset];

从NSManagedObjectContext重置方法文档:

From NSManagedObjectContext reset method documentation:


所有接收者的管理对象都被忘记了。如果你使用这个
方法,你应该确保你也丢弃了使用接收器获取的任何
管理对象的引用,因为它们

All the receiver's managed objects are "forgotten." If you use this method, you should ensure that you also discard references to any managed objects fetched using the receiver, since they will be invalid afterwards.

这篇关于核心数据 - 放弃更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆