如何通知我的NSFetchedResultsController我通过NSBatchUpdateRequest更改了一些对象?

时间:2015-10-19 12:18:11

标签: swift ios9 nsfetchedresultscontroller nsbatchupdaterequest

我创建了简单的NSBatchUpdateRequest

let bur = NSBatchUpdateRequest(entityName: "WLWishlist")
bur.predicate = NSPredicate(format: "name = %@", "oldname")
bur.propertiesToUpdate = ["name": "newname"]
bur.resultType = .UpdatedObjectsCountResultType

然后执行它们:

do {        
    let result = try NSManagedObjectContext.MR_defaultContext().executeRequest(bur) as? NSBatchUpdateResult
    print("------------- \(result!.result)")
} catch {
    print("error")
}

控制台上的输出是:

  

-------------可选(6)

但我管理相同对象的NSFetchedResultsController并不知道某事已被改变。如何通知NSFetchedResultsController这个?

1 个答案:

答案 0 :(得分:1)

首先,您必须将resultType更改为.UpdatedObjectIDsResultType

    bur.resultType = .UpdatedObjectIDsResultType

执行请求后,您必须遍历NSManagedObjectID并在NSManagedObejctContext中刷新它们。在此之后,您必须再次performFetch() NSFetchedResultsController

    do {

        let result = try context.executeRequest(bur) as? NSBatchUpdateResult
        if let ids = result?.result as? [NSManagedObjectID] {

            for id in ids {
                let object = context.objectWithID(id)
                context.refreshObject(object, mergeChanges: true)
            }
            try fetchedResultsController.performFetch()
        }

    } catch {
        print("error")
    }