概述
一、创建一个 Entity
二、Entity 的增删改查
一、创建一个 Entity
1、首先打开 .xcdatamodeld 文件,点击下方的 Add Entity 按钮,添加一个 Entity,命名为 Person
2、为 Person 添加两个 Attribute 分别为 Integer 16 类型的 age,String 类型的 name,如下图所示
屏幕快照 2019-07-03 下午2.39.56.png
3、创建一个 Person 对象
let entity = NSEntityDescription.entity(forEntityName: "Person", in: container.viewContext)!
let person = NSManagedObject(entity: entity, insertInto: nil) as! Person
return p
二、Entity 的增删改查
// 增
class func insert(_ obj: NSManagedObject) -> Void {
shared.container.viewContext.insert(obj)
}
// 删
class func delete(_ obj: NSManagedObject) -> Void {
shared.container.viewContext.delete(obj)
}
// 改
class func update(_ obj: NSManagedObject) -> Void {
shared.container.viewContext.refresh(obj, mergeChanges: true)
}
// 查
class func fetchPerson() -> [Person] {
let request: NSFetchRequest<Person> = NSFetchRequest(entityName: "Person")
do {
let result = try shared.container.viewContext.fetch(request)
return result
} catch {
fatalError("fetch Person error: \(error)")
}
}
使用了增、删、改方法后,需要调用 saveContext() 方法将数据保存
class func saveContext() -> Void {
let context = shared.container.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
fatalError("Save context error: \(error)")
}
}
}
完整的 CoreDataManager
class CoreDataManager {
static let shared = CoreDataManager()
lazy var container: NSPersistentContainer = {
let container = NSPersistentContainer(name: "SwiftCoreDataTest")
container.loadPersistentStores { (description, error) in
if let error = error {
fatalError("Unable to load persistent stores: \(error)")
}
}
return container
}()
private init() {
}
class func saveContext() -> Void {
let context = shared.container.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
fatalError("Save context error: \(error)")
}
}
}
class func person() -> Person {
let entity = NSEntityDescription.entity(forEntityName: "Person", in: shared.container.viewContext)!
let p = NSManagedObject(entity: entity, insertInto: nil) as! Person
return p
}
// 增
class func insert(_ obj: NSManagedObject) -> Void {
shared.container.viewContext.insert(obj)
}
// 删
class func delete(_ obj: NSManagedObject) -> Void {
shared.container.viewContext.delete(obj)
}
// 改
class func update(_ obj: NSManagedObject) -> Void {
shared.container.viewContext.refresh(obj, mergeChanges: true)
}
// 查
class func fetchPerson() -> [Person] {
let request: NSFetchRequest<Person> = NSFetchRequest(entityName: "Person")
do {
let result = try shared.container.viewContext.fetch(request)
return result
} catch {
fatalError("fetch Person error: \(error)")
}
}
}










网友评论