2016-12-20 40 views
3

我收到一个错误包括在NSPersistentContainer AppDelegate.swift:如何在Xcode 8使用夫特3.0

AppDelegate has no member 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() 
} 
} 

在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 
}() 
+0

尝试[这](HTTP:// stackoverflow.com/a/41040429/6536841)并通知是否无效。 –

+0

'viewContext'不是'NSPersistentStoreCoordinator'上的方法,它是'NSPersistentContainer'上的方法。 – Abizern

回答

8

先用进口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 
}() 

然后你可以这样写代码:

let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext 
+0

我已经导入CoreData框架。现在试着写你的代码了。它说“使用未声明的类型'NSPersitentContainer'即使在AppDelegate.swift文件中,默认的类方法'NSPersistentStoreCoordinator'也被显示为'NSPersistenContainer' –

+2

请在你的AppDelegate中写上persistentContainer类方法... –

+0

我做过。它报告'使用未声明的类型NSPersistentContainer' –