NSManagedObject:isUpdated和isInserted

mon*_*eta 8 iphone nsmanagedobject

我使用NSManagedObject类的isUpdated实例方法跟踪我的'对象'.

当我修改现有对象时,它可以正常工作.

如果我使用例如创建一个新对象:

[NSEntityDescription insertNewObjectForEntityForName:@"Entity" inManagedObjectContext:managedObjectContext]
Run Code Online (Sandbox Code Playgroud)

我不能使用isUpdated,我必须使用isInserted.

这是有效的,但我想检查,如果对象已被数据修改.

无论对象是否已被更改,isInserted都将返回FALSE,只有在插入或不插入时才会注意...

我能用什么?我可以跟踪对象属性的初始状态,但我更喜欢isUpdated方法.

谢谢!!!

Mus*_*afa 15

我不确定我是否完全理解你的问题,但是,如果你想检查你是否使用未保存的 NSManagedObject,你可以通过为NSManagedObject编写一个小类来做到这一点:

@interface NSManagedObject(Utility)

/**
 Returns YES if this managed object is new and has not yet been saved in the persistent store.
 */
- (BOOL)isNew;

@end

@implementation NSManagedObject(Utility)

- (BOOL)isNew {
    NSDictionary *vals = [self committedValuesForKeys:nil];
    return [vals count] == 0;
}

@end
Run Code Online (Sandbox Code Playgroud)

如果您使用以下方法创建了新的托管对象:

[NSEntityDescription insertNewObjectForEntityForName:@"Entity" inManagedObjectContext:managedObjectContext]
Run Code Online (Sandbox Code Playgroud)

您可以使用该-isNew方法检查是否已保存.