新增一個Entity in CoreData
Entity name : "Followers"
想法是這樣...
當登入後....
點到別的用戶...
紀錄一對一對的 (Follower, following)
follower -> 目前的登入用戶名
following -> 對那一個用戶有興趣的用戶名
用滑鼠點到相對應的tableview cell的同時
就會呼叫這個func ableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
首先 得到 相對應的 cell
let cell = tableView.cellForRow(at: indexPath)
// 把這個cell 打勾
cell?.accessoryType = UITableViewCellAccessoryType.checkmark
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath)
cell?.accessoryType = UITableViewCellAccessoryType.checkmark
// 同時把這個(follower, following)存起來
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")
}
}
當用戶時login
這個func 會每一個cell 都跑過一次...
該cell 就可以相對應到following 的名字
所以我們只要在這裡呼叫 fetchFollowers(username:user), 把這個following
傳進去
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
let user = username[indexPath.row]
// Configure the cell...
cell.textLabel?.text = user
fetchFollowers(username: user)
// 如果有, 就把這個cell打勾
if isFollowing[user]!{
cell.accessoryType = UITableViewCellAccessoryType.checkmark
}
return cell
}
然後再 fetchFollowers裡面判斷
這個func 的重點是
request.predicate = NSPredicate(format: "follower = %@ AND following = %@ ", self.currentuser,username)
兩個條件都要成立.. 用 AND
func fetchFollowers(username: String){
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let request = NSFetchRequest<NSFetchRequestResult>(entityName:"Followers")
//request.predicate = NSPredicate(format: "following = %@", username)
request.predicate = NSPredicate(format: "follower = %@ AND following = %@ ", self.currentuser,username)
request.returnsObjectsAsFaults = false
do{
let results = try context.fetch(request)
if results.count > 0 {
self.isFollowing[username] = true
}else{
self.isFollowing[username] = false
}
}catch{
print("Could not fetch results")
}
}
沒有留言:
張貼留言