Сортировка дескрипторов с помощью NSFetchedResultsController - Swift
У меня есть UITableView
кормили из Core Data
с NSFetchedResultsController
возвращение объектов Location. Сортировка по умолчанию (и заголовки разделов) осуществляется по первой букве имени объекта. Это работает (хотя я все еще пытаюсь правильно объединить верхний и нижний регистр в один и тот же раздел.) Пользователь может выбрать порядок таблицы по одной из трех необязательных категорий (которые являются атрибутами объекта), а затем эти категории отсортированы по имени организации.
Когда я устанавливаю сортировку по категории, я получаю следующую ошибку во время выполнения:
[_TtCSs23_ContiguousArrayStorage00007F80513B59D0 key]: unrecognized selector sent to instance 0x7f80513b5720
Это мое NSFetchedResultsController
:
var sectionNameKeyPathString1: String?
var sectionNameKeyPathString2: String?
var fetchedResultsController: NSFetchedResultsController {
if _fetchedResultsController != nil {
return _fetchedResultsController!
}
let fetchRequest = NSFetchRequest()
// Edit the entity name as appropriate.
let entity = NSEntityDescription.entityForName("Location", inManagedObjectContext: self.managedObjectContext!)
fetchRequest.entity = entity
// Set the batch size to a suitable number.
fetchRequest.fetchBatchSize = 20
// Edit the sort key as appropriate.
if sectionNameKeyPathString1 != nil {
let sortDescriptor1 = NSSortDescriptor(key: sectionNameKeyPathString1!, ascending: true)
let sortDescriptor2 = NSSortDescriptor(key: sectionNameKeyPathString2!, ascending: true)
let sortDescriptors = [sortDescriptor1, sortDescriptor2]
fetchRequest.sortDescriptors = [sortDescriptors]
} else {
let sortDescriptor = NSSortDescriptor(key: "locationName", ascending: true)
fetchRequest.sortDescriptors = [sortDescriptor]
}
var sectionNameKeyPath: String
if sectionNameKeyPathString1 == nil {
sectionNameKeyPath = "firstLetterAsCap"
} else {
sectionNameKeyPath = sectionNameKeyPathString1!
}
// 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.managedObjectContext!, sectionNameKeyPath: sectionNameKeyPath, cacheName: "Locations")
aFetchedResultsController.delegate = self
_fetchedResultsController = aFetchedResultsController
var error: NSError? = nil
if !_fetchedResultsController!.performFetch(&error) {
// TODO: Handle this error
// Replace this implementation with code to handle the error appropriately.
// abort() 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.
//println("Unresolved error \(error), \(error.userInfo)")
abort()
}
return _fetchedResultsController!
}
Используя точки останова, я уверен, что, например, sectionNameKeyPathString1 = "category1" и sectionNameKeyPathString2 = "locationName", а также что sectionNameKeyPath = "category1", поэтому путь к ключу соответствует дескриптору первой сортировки.
У меня это работало в Obj-C, но сейчас я вырываю волосы и уверен, что страдаю от слепоты.
1 ответ
У тебя просто слишком много []?
let sortDescriptors = [sortDescriptor1, sortDescriptor2] // <- an [NSSortDescriptor]
fetchRequest.sortDescriptors = [sortDescriptors] // <- now an [[NSSortDescriptor]]
должно быть просто:
fetchRequest.sortDescriptors = [sortDescriptor1, sortDescriptor2]