Share object state between View Controllers in IOS development

怎甘沉沦 提交于 2019-12-25 09:06:37

问题


My app has two tabs on a main TabViewController.

  • The first tab shows a list of the fruits I like.
  • The second tab send a request to an api while you type, searching for fruits with the name searched.

If the user clicks on any fruit, I'll show a fruit detail view, where It's possible to like the fruit (if it's already liked, you can unlike).

Now, I'm trying to achieve something like:

  • The user searchs for a fruit
  • The user likes the fruit
  • The user navigates back to the list
  • List shows the fruit with the "like" icon highlighted

How can I notify the list which I was before select row, the change of state of the cell (which was unliked and now is liked). How can I notify the OTHER list (in another tab) the same thing?

Thanks guys

EDIT

I'll try to show a real sample! When you go to the appstore and search for GMAIL

Then you go to featured (charts, I don't know in your country), and look for the same app

When you download it in any of those view controllers, at the same time the other controller shows the same status. It is exactly what I want to do.


回答1:


Simple way is you create one singleton class with array fruit. Example: You have model Fruit:

class Fruit {
       var name: String?
       var isLike: Bool?
}
class List: NSObject {
    static let sharedInstance = APIRequest()
    var fruits = [Fruit]()
}

Every viewcontroler can access it:

var list = List.sharedInstance

Every time 1 fruit has liked or unliked, change property of that fruit, and using NSNotification to notify the change to orther viewcontrollers. Viewcontroller which receive notification will access fruit list of singleton class.



来源:https://stackoverflow.com/questions/42111829/share-object-state-between-view-controllers-in-ios-development

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!