1. 新建项目时 勾选CoreData
2.新建Person类继承NSManagedObject (需要 import CoreData)并添加相应的属性
3.打开 工程名.xcdatamodeld 点击Add Entity
4.修改Entity为Person (设置属性栏 Entity->Name:Person ; Class->Name:Person;Class->Module:Current...)
5. 新建一个工具类(直接上代码)
importUIKit
importCoreData
privateletappDelegate =UIApplication.shared.delegateas!AppDelegate
privateletmanagedContext =appDelegate.persistentContainer.viewContext
classCoreDataTools:NSObject{
/**增加
*/
funcaddCoreData(modelName:String,block:(_object:NSManagedObject) -> ()) {
letemployee =NSEntityDescription.insertNewObject(forEntityName: modelName, into:managedContext)
block(employee)
do{
trymanagedContext.save()
print("add success")
}catch{
print("add failure")
}
}
/**查询
*闭包返回所需条件(返回nil则是查询所有)
*/
funcselectDataCoreData(modelName:String,special:()->NSPredicate?) -> [Any]? {
letemployeesFetch :NSFetchRequest =NSFetchRequest(entityName: modelName)
letspecial = special()
employeesFetch.predicate= special
do{
letarr =trymanagedContext.fetch(employeesFetch)
print("select success")
returnarr
}catch{
print("select failure")
returnnil
}
}
}
二:测试部分
CoreDataTools().addCoreData(modelName:"Person") { (object) -> ()in
letemp = objectas!Person
emp.name="hxy"
num=num+1
}