简体   繁体   English

CoreData通过其属性和关系比较两个NSManagedObjects

[英]CoreData compare two NSManagedObjects by their attributes and relationships

I have filter object. 我有过滤器对象。 It has several attributes and relationships. 它有几个属性和关系。 I want to create new filter object if there's no one with the same attributes & relationships. 如果没有具有相同属性和关系的人,我想创建新的过滤器对象。 How to accomplish this ? 怎么做到这一点?

I would choose a more general approach.. I would take the NSEntityDescriptions of the object and build a predicate with all properties in that Description. 我会选择一种更通用的方法..我会使用对象的NSEntityDescriptions并使用该描述中的所有属性构建谓词。

so like.. 所以..

- (void)insertIfUnique:(NSManagedObject*)obj inContext:(NSManagedObjectContext*)ctx {

NSMutableString *format = [NSMutableString string];

NSEntityDescription *desc = obj.entity;
NSArray *attrs = desc.attributeKeys;

for(NSString *attr in attrs) {
    if(format.length)
        [format appendString:@" AND "];
    [format appendFormat:@"%@==%@", attr, [obj valueForKey:attr]];
}

NSPredicate *p = [NSPredicate predicateWithFormat:format];
NSFetchRequest *f = [[NSFetchRequest alloc] initWithEntityName:desc.name];
f.predicate = p;
if([ctx countForFetchRequest:f error:nil]==0)
    [ctx insertObject:obj];

}

You have to manually search CoreData for any existing filter objects. 您必须手动搜索CoreData以查找任何现有过滤器对象。 If not found, you can process to create a new filter: 如果未找到,您可以进行处理以创建新过滤器:

Here is one helper function 这是一个辅助函数

+(id)uniqueEntityfForName:(NSString *)name 
                withValue:(id)value 
                   forKey:(NSString *)key
   inManagedObjectContext:(NSManagedObjectContext *)context {

    NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];    
    request.entity = [NSEntityDescription entityForName:name inManagedObjectContext:context];
    request.predicate = [NSPredicate predicateWithFormat:[key stringByAppendingString:@" == %@"], value];
    NSArray *result = [context executeFetchRequest:request error:nil];

    id entity = [result lastObject];
    if (entity == nil) {
        entity = [NSEntityDescription insertNewObjectForEntityForName:name inManagedObjectContext:context];
        [entity setValue:value forKey:key];
    } else {
        entity = [result lastObject];
    }

    return entity;
}

I use this method like this: 我使用这样的方法:

SomeEntity *entity = [CDUtils uniqueEntityfForName:@"SomeEntity" withValue:@"foo" forKey:@"bar" inManagedObjectContext:context];

You may have to define your own predicate. 您可能必须定义自己的谓词。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM