如何在Xcode 8中使用Swift 3.0在AppDelegate.swift中包含NSPersistentContainer

Kar*_* Sk 6 core-data ios swift swift3

我收到一个错误:

AppDelegate没有成员persistentContainer

import UIKit
import CoreData
class ViewController: UIViewController {

override func viewDidLoad() {
super.viewDidLoad()
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext // Error: value of type 'AppDelegate' has no member 'persistentContainer'
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
Run Code Online (Sandbox Code Playgroud)

在AppDelegate.swift文件中,NSPersistentStoreCoordinator被定义为默认值.

lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
}
catch {
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
Run Code Online (Sandbox Code Playgroud)

Pra*_*ani 16

您应首先导入CoreData框架,然后编写此代码:

lazy var persistentContainer: NSPersistentContainer = {

    let container = NSPersistentContainer(name: "Your Model File Name")
    container.loadPersistentStores(completionHandler: { (storeDescription, error) in
        if let error = error {

            fatalError("Unresolved error, \((error as NSError).userInfo)")
        }
    })
    return container
}()
Run Code Online (Sandbox Code Playgroud)

然后你应该这样写:

 let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
Run Code Online (Sandbox Code Playgroud)

  • 我已经导入了CoreData框架。现在也尝试编写您的代码。它说“使用未声明的类型‘NSPersitentContainer’。即使在 AppDelegate.swift 文件中,默认的类方法‘NSPersistenStoreCoordinator’也显示为‘NSPersistenContainer’。 (2认同)
  • 请在AppDelegate中写上persistentContainer类方法... (2认同)