Share object state between View Controllers in IOS

2019-09-11 03:45发布

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 First image, looking for an app

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

Same app in another view controller

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. download started by me on search list item shows status downloading on others lists

1条回答
\"骚年 ilove
2楼-- · 2019-09-11 04:24

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.

查看更多
登录 后发表回答