先得到 appDel let appDel = UIApplication.shared.delegate as? AppDelegate
在得到 context guard let context = appDel?.persistentContainer.viewContext else{ return }
do{
let results = try context.fetch(User.fetchRequest())
// 這邊 results 是一個陣列
// 使用一個for loop 去掃
for item in results{
guard let thisUser = item as? User else{ return }
print("\(thisUser.username)")
print("\(thisUser.password)")
}
}catch{
}
存檔
let aUser = User(context: context)
aUser.username = "Thomas"
aUser.password = "1234"
appDel?.saveContext() -> 重點是這一行
刪除
context.delete(thisUser)
appDel?.saveContext()
-----------------------------------------------------------------
override func viewDidLoad() {
super.viewDidLoad()
let appDel = UIApplication.shared.delegate as? AppDelegate
guard let context = appDel?.persistentContainer.viewContext else{ return }
do{
let results = try context.fetch(User.fetchRequest())
//let aUser = results[0] as? User
//aUser?.password = "87654321"
//appDel?.saveContext()
for item in results{
guard let thisUser = item as? User else{ return }
/*
if thisUser.username == "wei wei"{
//thisUser?.password = "11112222"
context.delete(thisUser)
appDel?.saveContext()
}*/
print("\(thisUser.username)")
print("\(thisUser.password)")
}
}catch{
}
}
沒有留言:
張貼留言