获取包含ID核心数据

时间:2016-09-13 05:18:13

标签: ios swift core-data nsfetchrequest swift3

我如何获取这些数据

[Account1,Account3]

in

[Account1,Account2,Account3,Account4,..](id entity)

with account1& account3 id

我尝试了以下代码,但它有一些随机帐户,不是特定于帐户1和帐户3。

        var ids = [account1id, account3id]

        let fetchRequest: NSFetchRequest<Accounts> =  Accounts.fetchRequest()
        let titleSort = NSSortDescriptor(key: "type", ascending: true)
        fetchRequest.sortDescriptors = [titleSort]
        fetchRequest.predicate = NSPredicate(format: "ANY %@ IN id", argumentArray: ids)

        var controller: NSFetchedResultsController<Accounts>
        if #available(iOS 10.0, *) {

            controller = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)

        } else {
            // Fallback on earlier versions
            controller = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: contexts, sectionNameKeyPath: nil, cacheName: nil)

        }


        do {

            try controller.performFetch()
            let tes = controller.fetchedObjects!
            print("check: \(tes.count) \(tes)")

        } catch {

            let error = error as NSError
            print("\(error)")

        }

2 个答案:

答案 0 :(得分:0)

试试这个:

var ids = [id1, id2]
fetchRequest.predicate = NSPredicate(format: "ANY %K IN %@", 
                                   argumentArray: [id, ids])

答案 1 :(得分:0)

您的谓词中不需要ANY,因为您没有使用多对多关系。您的IN也是错误的方式。它应该是:

NSPredicate(format: "id IN %@", argumentArray: ids)