CoreData中NSManagedObject的子类如何复写 hash 和 isEqual 方法


我借助CoreData从数据库中抓取到的若干对象. 懂CoreData的都知道会返回一个数组.
我的需求是: 我如果往数据库中新增一条记录,为了判断该对象不是已经存在的重复对象.我复写了父类的hash 和 isEqual 两个方法.
问题:
1. 我测试多次,如果仅仅是简单的 NSObject 的子类的话就可以没有任何问题的正常进行对象间的比较.但是在NSManagedObject的子类复写这俩方法就不行!
2. 是不是CoreData机制提供了另外的选择,如果有的话,麻烦您分享一下.

**好吧,我刚看了文档,说严禁覆盖. **
Methods you Must Not Override

NSManagedObject itself customizes many features of NSObject so that managed objects can be properly integrated into the Core Data infrastructure. Core Data relies on NSManagedObject’s implementation of the following methods, which you therefore absolutely must not override: primitiveValueForKey:, setPrimitiveValue:forKey:, isEqual:, hash, superclass, class, self, isProxy, isKindOfClass:, isMemberOfClass:, conformsToProtocol:, respondsToSelector:, managedObjectContext, entity, objectID, isInserted, isUpdated, isDeleted, and isFault, alloc, allocWithZone:, new, instancesRespondToSelector:, instanceMethodForSelector:, methodForSelector:, methodSignatureForSelector:, instanceMethodSignatureForSelector:, or isSubclassOfClass:.

报错如下:
请输入图片描述

objective-c sqlite

害羞的膀胱 12 years, 10 months ago

“判断该对象不是已经存在的重复对象”的标准是什么?是数据都相同?
能不能加一个比如uuid之类的用来判断?

Core Data保证了在同一线程下,同样的NSManagedObject取出来之后,他们就是同一个对象,可能是因为这个原因,所以不允许覆写你说的这两个方法。

变通的这样的实现能不能达到你的需求?

   
  + (AppAttachment *)insertOrGetAppAttachmentWithProperties:(NSDictionary *)properties inManagedObjectContext:(NSManagedObjectContext *)managedObjectContext
  
{
assert(properties != nil);
assert(managedObjectContext != nil);

AppAttachment *appAttachment = [AppAttachment MR_findFirstByAttribute:@"attachmentID" withValue:[properties objectForKey:@"id"] inContext:managedObjectContext];

if (appAttachment) {
return appAttachment;
}
else {
return [AppAttachment insertAppAttachmentWithProperties:properties inManagedObjectContext:managedObjectContext];
}
}

插入这条记录之前,查询这个ID是不是已经存在了,存在了就直接返回这条记录,否则新建一条,返回。

xiaozui answered 12 years, 10 months ago

Your Answer