以前使用过OC版本的CoreData应该很好理解Swift方式,所以这里简单的展示一下,增删改查的方法使用,同时给大家说一下创建步骤,方便大家的使用,转载请注明出处,谢谢~
步骤一:创建一个Swift的新项目,记得勾选对应的配置项,如图:
步骤二:打开****.xcdatamodeld文件,点击Add Entity,添加一个实体类,可以自己重定义类名,然后在类中添加属性,如图:
步骤三:打开AppDelegate文件,添加相关代码,注意红色的地方要改成自己项目中对应的名称
//MARK:------注意下面的四个方法需要自己添加
lazy var applicationDocumentsDirectory: URL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "me.appkitchen.cd" in the application's documents Application Support directory.
let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = Bundle.main.url(forResource: "SwiftCoreDataDemo", withExtension: "momd")!
return NSManagedObjectModel(contentsOf: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.appendingPathComponent("OneOneEntity.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" as AnyObject?
dict[NSLocalizedFailureReasonErrorKey] = failureReason as AnyObject?
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
步骤四:开始写自己的增删该查方法
//增加数据
func saveData(textStr:String) {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let manageContext = appDelegate.managedObjectContext
let entityOne = NSEntityDescription.entity(forEntityName: "OneOneEntity", in: manageContext)
let itemS = NSManagedObject.init(entity: entityOne!, insertInto: manageContext)
itemS.setValue(textStr, forKey: "textStr")
do {
try manageContext.save()
self.dataArray.append(itemS)
//print("..........\(itemS)")
} catch {
print("存储错误...")
}
}
//删除
func deleteData(aIndexPath:IndexPath) {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let manageContext = appDelegate.managedObjectContext
manageContext.delete(self.dataArray[aIndexPath.row])
do {
try manageContext.save()
self.dataArray.remove(at: aIndexPath.row)
self.myTableView.reloadData()
} catch {
print("存储错误...")
}
}
//修改
func updateData(aIndxPath:IndexPath,upStr:String) {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let manageContext = appDelegate.managedObjectContext
//let entityOne = NSEntityDescription.entity(forEntityName: "OneOneEntity", in: manageContext)
//创建查询请求
let fetchRequest = NSFetchRequest<NSFetchRequestResult>.init(entityName: "OneOneEntity")
//获取数据
do {
let results = try manageContext.fetch(fetchRequest)
//找到修改的数据
let oneObj:NSManagedObject = results[aIndxPath.row] as! NSManagedObject
oneObj.setValue(upStr, forKey: "textStr")
do {
try manageContext.save()
do {
let results1 = try manageContext.fetch(fetchRequest)
self.dataArray = results1 as! [NSManagedObject]
self.myTableView.reloadData()
} catch {
print("查询错误...")
}
} catch {
print("存储错误...")
}
} catch {
print("修改错误...")
}
}
//查询
func lookUpData() {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let manageContext = appDelegate.managedObjectContext
let fetchReq = NSFetchRequest<NSFetchRequestResult>(entityName: "OneOneEntity")
do {
let results = try manageContext.fetch(fetchReq)
self.dataArray = results as! [NSManagedObject]
self.myTableView.reloadData()
} catch {
print("查询错误...")
}
}
效果图:(具体代码,请自行研究,如果喜欢请点Star,源码:https://github.com/hbblzjy/SwiftCoreDataDemo)