其他人也问过类似的问题,但给出的答案对我没有帮助。我正在尝试使用核心数据创建一个表视图,并且我一直收到一条错误消息,表明我的fetchRequest和/或managedObjectContext是nil
class CustomTableViewController: UITableViewController,
NSFetchedResultsControllerDelegate {
var coreDataContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
@available(iOS 10.0, *)
fileprivate lazy var fetchedResultsController: NSFetchedResultsController<Movie> = {
// Initiate the query
let fetchRequest: NSFetchRequest<Movie> = Movie.fetchRequest() as! NSFetchRequest<Movie>
// Sort the data
fetchRequest.sortDescriptors = [NSSortDescriptor(key:"title", ascending: true)]
NSLog("Request: %@, Context: %@", fetchRequest, self.coreDataContext);
let fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.coreDataContext, sectionNameKeyPath: nil, cacheName: nil)
fetchedResultsController.delegate = self
return fetchedResultsController
}()
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.setToolbarHidden(false, animated: false)
do {
// when view loads, run the fetch (query)
if #available(iOS 10.0, *) {
try self.fetchedResultsController.performFetch()
} else {
// Fallback on earlier versions
}
} catch {
let fetchError = error as NSError
print("Unable to Perform Fetch Request")
print("\(fetchError)")
}
}
有没有人有任何想法有什么不对?此外,不确定它是否重要,但我的项目是Objective-C和Swift的混合
此外,我上面代码中的NSLog("Request: %@, Context: %@", fetchRequest, self.coreDataContext)
打印出来:
Request: (null), Context: <NSManagedObjectContext: 0x1701db4e0>
我的xcdatamodeld中有一个名为Movie的实体,它有三个String属性。我还在自己的Movie.swift文件中创建了一个类似于Movie的类:
import UIKit
import CoreData
class Movie: NSManagedObject {
}