Chr*_*ris 14 model core-data objective-c
希望有人能解释发生了什么.
如果我从Core Data模型中获取了一个对象,请修改一个不持久或甚至在模型中定义的属性!然后再次销毁并获取对象,该值仍然是先前设置的.
为什么是这样?
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;
Run Code Online (Sandbox Code Playgroud)
输出是:
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;
}
Run Code Online (Sandbox Code Playgroud)
Rog*_*Rog 24
请记住,您对所有托管对象所做的更改将保留在Coredata的托管对象上下文中,直到您保留它们(即保存上下文).
因此,在您的情况下,您正在对托管对象进行更改,将其引用设置为nil但不重置上下文.
这意味着您的更改仍然有效,下次您获取相同的对象时,它将被应用.
要完全摆脱它,您需要重置上下文:
[context reset];
Run Code Online (Sandbox Code Playgroud)
从NSManagedObjectContext重置方法文档:
所有接收方的托管对象都被"遗忘".如果使用此方法,则应确保还丢弃对使用接收方获取的任何托管对象的引用,因为它们之后将无效.
Core Data缓存对象,缓存可能会保留未定义属性的ivars.
[context refreshObject:promotion mergeChanges:NO]然后尝试日志语句.
| 归档时间: |
|
| 查看次数: |
6607 次 |
| 最近记录: |