Avijit Nagare
Avijit Nagare

Reputation: 8782

iOS: Check value is matches with any attribute of entity in core data?

I have entity in code data called "Location" and "Location" entity have around 50 attributes.

I used following predicate to check given value matches with any attribute from "Location" entity (i don't want to match it with any particular attribute but all attribute from entity)

NSString *enumKey=@"Pune";
NSArray *enumListForDeleteArray= [[CoreDataModel sharedCoreDataModel] arrayOfRecordsForEntity:@"Location" andPredicate:[NSPredicate predicateWithFormat:@"%@",enumKey] andSortDescriptor:nil forContext:nil];

Problem: What should be my predicate which ensure that value "Pune" is matches with any attribute from "Location" ?

Kindly suggest NSPredicate value.

EIDT

 NSString *enumKey = @"abc"; 
 NSEntityDescription *entity = [NSEntityDescription entityForName:@"Location" inManagedObjectContext:[[CoreDataModel sharedCoreDataModel] getNewManagedObjectContext]];//
 NSMutableArray *orPredicateArray=[[NSMutableArray alloc] init];
 for(NSDictionary *attributeName in entity.attributesByName) {
    [orPredicateArray addObject:[NSPredicate predicateWithFormat:@"%K == %@",attributeName,enumKey]];
 }
NSCompoundPredicate *combinedPredicate = [NSCompoundPredicate orPredicateWithSubpredicates:orPredicateArray];
NSArray *enumKeyReferenceArray= [[CoreDataModel sharedCoreDataModel] arrayOfRecordsForEntity:@"Location" andPredicate:combinedPredicate andSortDescriptor:nil forContext:nil];

There is now "abc" value in any of attribute but still i am getting object for "Location" ?

Upvotes: 0

Views: 341

Answers (1)

Tom Harrington
Tom Harrington

Reputation: 70946

You can't create a predicate that matches all properties unless the predicate lists every single property. There's no "wildcard" matching or "all properties" option. Your predicate would have to be something like attrib1 == "value" OR attrib2 == "value" OR ....

This is possible but it will be extremely slow. For every instance you check, you will need to do one string comparison per attribute. In your case, 50 string comparisons for every object you save. You should consider changing your requirements, if possible, because the results will not be good.

You could dynamically build a predicate with something like the following. I don't recommend it, for reasons described above, but it should work-- slowly.

let entity = // The NSEntityDescription you're fetching
let stringToMatch = // the string you want to look for
var attributePredicates = [NSPredicate]()

for (attributeName, attribute) in entity.attributesByName {
    if attribute.attributeType == .stringAttributeType {
        let newPredicate = NSPredicate(format: "%K = %@", attributeName, stringToMatch)
        attributePredicates.append(newPredicate)
    }
}
let combinedPredicate = NSCompoundPredicate(orPredicateWithSubpredicates: attributePredicates)

Upvotes: 4

Related Questions