Reputation: 97
I am doing a swift project, the UI design is already given like the following picture.
PROBLEM I need to pass data bidirectionally between Profile view controller and Home view controller.
I already tried: Inside Home view controller:
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
NotificationCenter.default.addObserver(self, selector: #selector(selectMypost), name: NSNotification.Name("com.rjt.Chao.postsCliked"), object: nil)
}
@objc func selectMypost(){
isFiltering = true
if let currentUserId = Auth.auth().currentUser?.uid {
filteredPosts = posts.filter{
$0.userID == currentUserId
}
}
tblview.reloadData()
}
and
func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
guard let curUserId = Auth.auth().currentUser?.uid else {return false}
let count = posts.filter{$0.userID == curUserId}.count
NotificationCenter.default.post(name: NSNotification.Name("com.rjt.Chao.mypostnumbercount"), object: self, userInfo: ["currentUserPostCount":count])
print(viewController)
return true
}
Inside Profile view controller:
@objc func changeCounts(notification:Notification){
guard let count = notification.userInfo!["currentUserPostCount"] else {return}
posts.setTitle(String(count as! Int), for: .normal)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
NotificationCenter.default.addObserver(self, selector: #selector(changeCounts), name: NSNotification.Name("com.rjt.Chao.mypostnumbercount"), object: nil)
}
But when I clicked on the Profile tab item for the first time, the selector function was not called, the UIButton title is not changed.
My Guess: seems that observer should be added before the notification post. Am I right?
How to fix this?
Upvotes: 1
Views: 86
Reputation: 590
Create a global struct/static class that you can store information inside of (pick whichever suites your needs the most). Look into MVC and Singleton design patterns. Basically, MVC is a pattern that involves completely separating your data and your VCs, so that your views and controllers only handle UI stuff, and whenever they need to access info, they access your data classes. A singleton is more what I suggested at the top. A single struct/class (usually a class), that holds data for your application.
Upvotes: 1