ManagedObjectContext в Swift 3
Я хочу работать через этот примерный код, в котором Swift и CoreData используются для создания таблицы. Однако, используя Swift 3, я не могу заставить его работать. Самое главное, я не могу правильно заменить строку
// set up the NSManagedObjectContext
let appDelegate = NSApplication.sharedApplication().delegate as! AppDelegate
managedContext = appDelegate.managedObjectContext
хотя я нашел этот связанный вопрос (который, однако, не iOS, а не OS X). Как я могу заменить этот фрагмент кода, который выдает сообщение об ошибке Value of type 'AppDelegate' has no member 'managedContext'
?
Ответы
Ответ 1
Swift 3 в macOS
let appDelegate = NSApplication.shared().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
Приведенная вами ошибка говорит 'AppDelegate' has no member 'managedContext'
вместо 'AppDelegate' has no member 'managedObjectContext'
, что приведет меня к выводу, что вам просто нужно исправить свой синтаксис.
Swift 3 в iOS 10
Для основных данных требуется как минимум 3 вещи для работы:
-
- Модель управляемого объекта
- Постоянный координатор магазина
- И контекст управляемого объекта
Поместите эти три вещи вместе, и вы получите Core Data Stack.
Когда вышел iOS 10, был введен новый объект, называемый NSPersistentContainer, который инкапсулирует основной стек данных.
Как создать объект контейнера отвечает здесь.
managedObjectContext
теперь является свойством viewContext
, доступ к которому осуществляется через:
let delegate = UIApplication.shared.delegate as! AppDelegate
let managedObjectContext = delegate.persistentContainer.viewContext
Полезная статья Что нового в основных данных, но если это чтение кажется слишком тяжелым, это WWDC видео отлично справляется с этой темой.
Ответ 2
AppDelegate
имеет только члены
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// 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.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
поэтому используйте
let managedContext = (UIApplication.shared.delegate as! appDelegate).persistentContainer.viewContext
Это будет прекрасно работать
Ответ 3
Я быстро 3 вы можете получить managedContext, установленный этим кодом:
let managedContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
Ответ 4
Для macOS и Swift 3.1
let moc: NSManagedObjectContext = (NSApplication.shared().delegate as! AppDelegate).persistentContainer.viewContext