想法是這樣的...
一樣是做在 tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
當用戶點擊到某一個cell時會呼叫這個func
然後去判斷 isFollowing[user]
如果是 false -> 添加關注
true -> 刪除關注
然後再加入刪除關注的動作
把原本的 cell?.accessoryType 設成 UITableViewCellAccessoryType.none
刪除Core data 裡面的這組data.. 記得也要把 isFollowing[user] 的狀態改變
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath)
let user = username[indexPath.row]
if isFollowing[user]!{
isFollowing[user] = false
cell?.accessoryType = UITableViewCellAccessoryType.none
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Followers")
request.predicate = NSPredicate(format: "follower = %@ AND following = %@", currentuser, user )
request.returnsObjectsAsFaults = false
do{
let results = try context.fetch(request)
if results.count > 0 {
for result in results as! [NSManagedObject] {
context.delete(result)
do{
try context.save()
}catch{
print("delete failure")
}
}
}
}catch{
print("Could not fetch result")
}
}else{
isFollowing[user] = true
cell?.accessoryType = UITableViewCellAccessoryType.checkmark
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let follower = NSEntityDescription.insertNewObject(forEntityName: "Followers", into: context)
follower.setValue(currentuser, forKey: "follower")
follower.setValue(username[indexPath.row], forKey: "following")
do{
try context.save()
}catch{
print("could not save followers data")
}
}
}
沒有留言:
張貼留言