1 建立自己的CoreDataStack
ViewController 指的是导航层中的第一个视图
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是导航视图指向的第一个控制器
return true
}
viewController.managedContext = coreDataStack.managedContext
return true
}
2 数据建模
File\New\File..., 选 iOS\Core Data\Data Model template Name the file 库名.xcdatamodeld。
然后在新建的模型中,点Add Entity 按钮添加添加一个相当于数据库中的表名。
然后同理右边添加“字段名”
Codegen最好改成Manual 要不然可能有redeclaration报错
3 添加managed object subclass
** Editor\Create NSManagedObject Subclass...** 选刚刚添加的Entity名字,一般默认一直继续下去就可以了。
网友评论