Bryan Deemer
Bryan Deemer

Reputation: 903

Swift Core Data Predicate IN Clause

I'm attempting to use an IN clause with an NSPredicate. I'm getting the following error:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSTaggedPointerString countByEnumeratingWithState:objects:count:]: unrecognized selector sent to instance 0xa000000000000611'

Here's the code:

let fetchRequest: NSFetchRequest<Employee> = NSFetchRequest(entityName: "Employee")

fetchRequest.sortDescriptors = [
     NSSortDescriptor.init(key: "lastName", ascending: true)
]

fetchRequest.predicate = NSPredicate(format: "ANY id IN %@", argumentArray: recentEmployeeIds)

fetchedResultsController = NSFetchedResultsController.init(fetchRequest: fetchRequest,
                                                                           managedObjectContext: FLCoreDataController.shared.mainObjectContext,
                                                                           sectionNameKeyPath: nil,
                                                                           cacheName: nil)
fetchedResultsController?.delegate = self

try? fetchedResultsController?.performFetch()

Any ideas as to what the problem is?

Upvotes: 8

Views: 6213

Answers (2)

doozMen
doozMen

Reputation: 730

You cannot remove the `argumentArray anymore (tested in swift 5.7)

Let duplicates = [“id”, “id2”]
let findDuplicates = <#NSManagedObject#>.fetchRequest()
findDuplicates.predicate = NSPredicate(format: <#key#> IN %@", argumentArray: [duplicates])

The difference is that you put the array in an array so it gets inserted as the first item. You only have one %@ so there should be in the array only 1 argument, but as you pass `duplicates which has 2 items there will be an error. Wrapping it in an array solves that.

Upvotes: 1

dmorrow
dmorrow

Reputation: 5694

You don't show how you are defining recentEmployeeIds, but assuming its something like

let recentEmployeeIds:[Int] = ...

then you need to init the NSPredicate correctly. There is no label for argumentArray

fetchRequest.predicate = NSPredicate(format: "ANY id IN %@", recentEmployeeIds)

Upvotes: 11

Related Questions