CoreData数据库操作
1.创建工程
2.对数据库操作
//创建student对象
let entityDes=NSEntityDescription.entity(forEntityName:"Student",in:self.getContext())
//给student赋值
let st=NSManagedObject(entity:entityDes!,insertInto:self.getContext())
st.setValue(17, forKey: "age")
st.setValue("小李", forKey: "name")
//保存对象
try! self.getContext().save()
print(NSTemporaryDirectory())
//查询
let request=NSFetchRequest<NSFetchRequestResult>(entityName:"Student")
//查找条件
let predicate=NSPredicate(format: "name='小王九'", argumentArray: nil)
request.predicate=predicate
let sort=NSSortDescriptor(key: "age", ascending: true)
//排序
request.sortDescriptors=[sort]
//分页
// request.fetchOffset=1
// request.fetchLimit=2
//执行查询
let arr=try!self.getContext().fetch(request) as! [NSManagedObject]
for item in arr{
let name=item.value(forKey: "name")
let age=item.value(forKey: "age")
print("name=\(name!) age=\(age!)")
//更新
//item.setValue("小王九", forKey: "name")
self.getContext().delete(item)
}
try! self.getContext().save()
}
//提供context
func getContext() -> NSManagedObjectContext {
let delegate=UIApplication.shared.delegate as! AppDelegate
let context=delegate.persistentContainer.viewContext
return context
}