简体   繁体   中英

NSArray as parameter in Core Data fetchRequest

I have database of about 10.000 entities and dynamic NSArray of 50 NSString elements. Would like to check if each of those elements exist in database and create new array of ones that exist. I don't need to return whole entities, just those NSString titles ( which are the same as in NSString array)

NSPredicate should compare entity.title to NSString element with EXACT match.


What is the best and processor/memory efficient way to do it?

I think that you should use the 'in' operation in your predicate to get your result. This lets you leverage the database to perform the comparison, instead of bringing back all of the 10,000 records to compare yourself. If you take this approach, your code could look like this:

// Assuming that arrayName is your existing array of values to match, that 
// EntityName is the object in CoreData that you’re looking at, and context
// is your moc

var newArray: [String] = []

let fetchRequest = NSFetchRequest<EntityName>(entityName: "EntityName")
fetchRequest.predicate = NSPredicate(format: "title in %@", arrayName)

do {
    result = try context.fetch(fetchRequest)
    for element in result {
        newArray.append(element.title)
    }
} catch {
     … manage any errors …
}

Note - I'm targeting Swift 3.0 compatible code - not sure if swift was what you're after.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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