NSFetchedResultsController和to-many关系不起作用

时间:2016-09-22 04:26:30

标签: core-data nspredicate nsfetchedresultscontroller swift3 nssortdescriptor

好的,在过去的1-2周里,我一直在搜索和尝试这种情况,但我没有得到它。我可以在没有NSFRC的情况下实现我想要的但是出于性能原因和方便,我想用NSFRC来做。 所以,我有一个包含2个实体的DataModel - 见图 to-many Relationship

有一个帐户,一个帐户可以有多个帐户变更 - 这是非常明显的。 所以我希望能够选择一个帐户,然后显示该特定帐户的所有AccountChanges。 到目前为止,我能够获取帐户并访问cellForRow函数中的NSSet,但我没有得到正确的部分和numberOfRowsInSection - 这是主要问题。

以下是一些代码:

    func numberOfSections(in tableView: UITableView) -> Int {

    print("Sections : \(self.fetchedResultsController.sections?.count)")
    if (self.fetchedResultsController.sections?.count)! <= 0 {
        print("There are no objects in the core data - do something else !!!")
    }
    return self.fetchedResultsController.sections?.count ?? 0
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    print("Section Name")
    print(self.fetchedResultsController.sections![section].name)
    let sectionInfo = self.fetchedResultsController.sections![section]
    print("Section: \(sectionInfo) - Sections Objects: \(sectionInfo.numberOfObjects)")
    return sectionInfo.numberOfObjects
}

有一些印刷陈述仅供参考!

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let myCell = myTable.dequeueReusableCell(withIdentifier: "myCell")! as UITableViewCell
    let accountBalanceChanges = self.fetchedResultsController.object(at: indexPath)
    print("AccountBalanceChanges from cell....")
    print(accountBalanceChanges)

    let details = accountBalanceChanges.accountchanges! as NSSet
    print("Print out the details:")
    print(details)
    let detailSet = details.allObjects
    let detailSetItem = detailSet.count // Just for information!


    let myPrint = detailSet[indexPath.row] as! AccountChanges
    let myVal = myPrint.category

    myCell.textLabel?.text = myVal

    return myCell
}

所以,我能够获取数据,但总是只有一个项而不是整个集 - 我猜是因为section / numberOfRows是错误的。

这是我的NSFRC

    var fetchedResultsController: NSFetchedResultsController<Accounts> {
    if _fetchedResultsController != nil {
        return _fetchedResultsController!
    }
    let fetchRequest: NSFetchRequest<Accounts> = Accounts.fetchRequest()
    // Set the batch size to a suitable number.
    fetchRequest.fetchBatchSize = 20
    // Edit the sort key as appropriate.

    let sortDescriptor = NSSortDescriptor(key: "aName", ascending: false)
    fetchRequest.sortDescriptors = [sortDescriptor]


    let predicate = NSPredicate(format: "(ANY accountchanges.accounts = %@)", newAccount!)
    fetchRequest.predicate = predicate
    // Edit the section name key path and cache name if appropriate.
    // nil for section name key path means "no sections".

    let aFetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.coreDataStack.context, sectionNameKeyPath: nil, cacheName: nil)
    aFetchedResultsController.delegate = self
    _fetchedResultsController = aFetchedResultsController

    do {
        try _fetchedResultsController!.performFetch()
    } catch {
        // Replace this implementation with code to handle the error appropriately.
        // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
        let nserror = error as NSError
        fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
    }

    return _fetchedResultsController!
}

我假设它是SortDescriptor或谓词 - 或者两者兼而有之?

任何帮助或至少方向都非常感谢。 我已经尝试了很多不同的方法,但没有一个给我正确的结果。

1 个答案:

答案 0 :(得分:1)

我会反过来说,我的意思是使用FRC来获取具有特定Id的帐户的所有更改,并使用以下谓词:

let predicate = NSPredicate(format: "accounts.aId = %@", ACCOUNTID)

let predicate = NSPredicate(format: "accounts = %@", account.objectID)

我会将帐户实体重命名为帐户,并将该关系重新命名为关系,因为它是一对一的关系。 假设您有一个包含所有帐户的表格视图,当您点击一个帐户时,它会返回其更改。

 var fetchedResultsController: NSFetchedResultsController<AccountChanges> {
    if _fetchedResultsController != nil {
        return _fetchedResultsController!
    }
    let fetchRequest: NSFetchRequest<AccountChanges> = AccountChanges.fetchRequest()
    // Set the batch size to a suitable number.
    fetchRequest.fetchBatchSize = 20
    // Edit the sort key as appropriate.

    let sortDescriptor = NSSortDescriptor(key: "aName", ascending: false)
    fetchRequest.sortDescriptors = [sortDescriptor]


    let predicate = NSPredicate(format: "accounts.aId = %@", ACCOUNTID)
    fetchRequest.predicate = predicate
    // Edit the section name key path and cache name if appropriate.
    // nil for section name key path means "no sections".

    let aFetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.coreDataStack.context, sectionNameKeyPath: nil, cacheName: nil)
    aFetchedResultsController.delegate = self
    _fetchedResultsController = aFetchedResultsController

    do {
        try _fetchedResultsController!.performFetch()
    } catch {
        // Replace this implementation with code to handle the error appropriately.
        // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
        let nserror = error as NSError
        fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
    }

    return _fetchedResultsController!
}

干杯