Хорошо, я искал и пытался в этом случае в течение последних 1-2 недель, и я не получил его работу. Я бы смог добиться того, чего хочу, без NSFRC, но по соображениям производительности и убежденности я хотел бы сделать это с NSFRC. Итак, у меня есть DataModel с 2 Entities - увидеть картину NSFetchedResultsController и to-many отношения не работают
Существует один аккаунт и один счет может иметь много accountchanges - что вполне очевидно. Итак, я хочу иметь возможность выбирать учетную запись, а затем показывать все учетные записи для этой конкретной учетной записи. До сих пор мне удалось получить учетную запись, а также получить доступ к NSSet в функции cellForRow, но я не получаю правильные разделы и 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
}
Таким образом, я могу получить данные, но всегда только один элемент, а не весь набор - Я думаю, из-за того, что разделы/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 или предикат - или, может быть, и другое?
Любая помощь или, по крайней мере, направления хорошо оценены. Я уже пробовал много разных подходов, но никто не давал мне правильных результатов.
Еще один комментарий, я пробовал много разных путей в SortDescriptor и в предикате/или sectionNameKeyPath из NSFRC - большинство отказов сообщения являются: «ко-многим ключевым здесь не допускается» или «keypath для (категория, название ...) не существует» Из кода выше предикат, похоже, работает, но SortDescriptor дает мне больше всего проблем ... мои догадки –