- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
我正在将一个现有项目从 Swift 2 重构到 Swift 3。在我开始重构 Core Data 之前,一切都很简单。我能够创建托管对象并将它们保存在 managedObjectContext
中,但我很难让 NSFetchedResultsController
工作。我看了一下 this post ,但这并没有让我越过终点线。
从 JSON 导入记录后,我使用以下代码验证 managedObjectContext
中是否存在对象:
func recordCount() -> Int {
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let fetchRequest: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest(entityName: "MyEntity")
let count = try! context.count(for: fetchRequest)
return count
}
当我创建一个 fetchedResultsController
时,我遇到了麻烦。我的代码没有崩溃,但它没有返回 NSManagedObjects
,尽管存在与我的搜索匹配的对象。
下面是我如何在 UIViewController
中创建我的 NSFetchedResultsController
。
class MyViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, NSFetchedResultsControllerDelegate {
// This is set on a prior viewController before segue.
// I've verified it's not nil
var selectedEquipmentString: String?
let managedObjectContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
lazy var fetchedResultsController: NSFetchedResultsController<MyEntity> = {
// I've tried altering the syntax of the fetchRequest
// let fetchRequest: NSFetchRequest<MyEntity> = MyEntity.fetchRequest()
let fetchRequest: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest(entityName: "MyEntity")
let sortDescriptor = NSSortDescriptor(key: "generalArea", ascending: true)
fetchRequest.sortDescriptors = [sortDescriptor]
fetchRequest.predicate = NSPredicate(format: "equipmentDescription == %@", self.selectedEquipmentString!)
let frc: NSFetchedResultsController<MyEntity> = NSFetchedResultsController(fetchRequest: fetchRequest as! NSFetchRequest<MyEntity>, managedObjectContext: self.managedObjectContext, sectionNameKeyPath: "generalArea", cacheName: nil)
frc.delegate = self
return frc
}()
// MARK: - View Lifecycle Methods (abbreviated)
override func viewDidLoad() {
super.viewDidLoad()
// I've tried moving this call to viewWillAppear and viewDidAppear without success
fetchObjectsFromManagedObjectContext()
}
// MARK: - Core Data Methods (abbreviated)
func fetchObjectsFromManagedObjectContext() {
do {
try fetchedResultsController.performFetch()
} catch {
print("error: \(error)")
return
}
print ("There are \(fetchedResultsController.fetchedObjects!.count) returned from fetchObjectsFromManagedObjectContext")
}
}
此代码不会崩溃,但不会从 fetchRequest 返回任何记录。我能够通过谓词中的拼写错误强制崩溃,但如果没有拼写错误,尽管对象与谓词匹配,但不会返回任何对象。
我欢迎任何关于我的错误的建议。我放心,我知道这将是一个非常愚蠢的疏忽。感谢您的阅读。
最佳答案
你的 NSFetchRequest 应该有一个类型 NSFetchRequest<MyEntity>
, 但您指定 NSFetchRequest<NSFetchRequestResult>
.尝试更改它,让我知道它是否有帮助
关于ios - 难以在 Swift 3 中配置 NSFetchedResultsController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39642827/
我想模拟这个函数: function getMetaData(key) { var deferred = $q.defer(); var s3 = vm.ini
我是一名优秀的程序员,十分优秀!