我设置了一个数组来保存核心数据中的数据。
var users:[Users] = []
当我想从tableView中删除我的一个数据时,我设置了这个函数,如下所示:
func deleteData(username:IndexPath){
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
context.delete(users[username.row])
print("test1")
print(users[username.row])
print(users)
print(users.count)
do {
try context.save()
print("test2")
print(users[username.row])
print(users)
print(users.count)
} catch {
print("Could'n save data")
}
}
我观察了这个操作,我在这里发现了一些问题:
在context.save()下面,我输入了print(用户),控制台显示了用户数据:
test2
<Users: 0x600000286770> (entity: Users; id: 0xd000000000e40000 <x-coredata://2D4CEBDA-C1B2-4CEC-A734-B7C9579C12A5/Users/p57> ; data: <fault>)
[<Users: 0x600000281ea0> (entity: Users; id: 0xd000000000c40000 <x-coredata://2D4CEBDA-C1B2-4CEC-A734-B7C9579C12A5/Users/p49> ; data: {
username = test1;
}), <Users: 0x6000002823f0> (entity: Users; id: 0xd000000000c80000 <x-coredata://2D4CEBDA-C1B2-4CEC-A734-B7C9579C12A5/Users/p50> ; data: {
username = test2;
}), <Users: 0x6000002823a0> (entity: Users; id: 0xd000000000cc0000 <x-coredata://2D4CEBDA-C1B2-4CEC-A734-B7C9579C12A5/Users/p51> ; data: {
username = test3;
}), <Users: 0x600000282350> (entity: Users; id: 0xd000000000d00000 <x-coredata://2D4CEBDA-C1B2-4CEC-A734-B7C9579C12A5/Users/p52> ; data: {
username = test4;
}), <Users: 0x600000282300> (entity: Users; id: 0xd000000000d40000 <x-coredata://2D4CEBDA-C1B2-4CEC-A734-B7C9579C12A5/Users/p53> ; data: {
username = test5;
}), <Users: 0x600000286770> (entity: Users; id: 0xd000000000e40000 <x-coredata://2D4CEBDA-C1B2-4CEC-A734-B7C9579C12A5/Users/p57> ; data: <fault>)]
6
但我只有5个数据,而不是6.这个问题出了什么问题?
答案 0 :(得分:0)
从Core Data中删除项目并不会自动将其从数据源阵列中删除。您必须明确删除它:
context.delete(users[username.row])
users.remove(at: username.row)