1 建立自己的CoreDataStack
ViewController 指的是導(dǎo)航層中的第一個(gè)視圖
1.1 CoreDataStack.swift
** File\New\File...**, 選 iOS\Source\Swift。取名 **CoreDataStack.swift **旋廷。
import CoreData
class CoreDataStack {
private let modelName: String
init(modelName: String) {
self.modelName = modelName
}
private lazy var storeContainer: NSPersistentContainer = {
let container = NSPersistentContainer(name: self.modelName)
container.loadPersistentStores {
(storeDescription, error) in
if let error = error as NSError? {
print("Unresolved error \(error), \(error.userInfo)")
}
}
return container
}()
lazy var managedContext: NSManagedObjectContext = {
return self.storeContainer.viewContext
}()
func saveContext() {
guard managedContext.hasChanges else { return }
do {
try managedContext.save()
} catch let error as NSError {
print("Unresolved error \(error), \(error.userInfo)")
}
}
}
1.2 ViewController
import CoreData
然后添加屬性
var managedContext: NSManagedObjectContext!
1.3 AppDelegate
lazy var coreDataStack = CoreDataStack(modelName: "UserRecords")
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
// CoreData
guard let navController = window?.rootViewController as? UINavigationController,
let viewController = navController.topViewController as? MainViewController else { // MainViewController是導(dǎo)航視圖指向的第一個(gè)控制器
return true
}
viewController.managedContext = coreDataStack.managedContext
return true
}
2 數(shù)據(jù)建模
File\New\File..., 選 iOS\Core Data\Data Model template Name the file 庫名.xcdatamodeld辈毯。
然后在新建的模型中倒慧,點(diǎn)Add Entity 按鈕添加添加一個(gè)相當(dāng)于數(shù)據(jù)庫中的表名站玄。
然后同理右邊添加“字段名”
Codegen最好改成Manual 要不然可能有redeclaration報(bào)錯(cuò)
3 添加managed object subclass
** Editor\Create NSManagedObject Subclass...** 選剛剛添加的Entity名字枚驻,一般默認(rèn)一直繼續(xù)下去就可以了。