IOS开发中View Controllers之间共享对象状态 [英] Share object state between View Controllers in IOS development

查看:35
本文介绍了IOS开发中View Controllers之间共享对象状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序在主 TabViewController 上有两个选项卡.

My app has two tabs on a main TabViewController.

  • 第一个标签显示了我喜欢的水果列表.
  • 第二个选项卡会在您键入时向 api 发送请求,以搜索名称搜索水果.

如果用户点击任何水果,我会显示一个水果详细信息视图,其中可能会喜欢该水果(如果已经喜欢,您可以不喜欢).

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:

  • 用户搜索水果
  • 用户喜欢这个水果
  • 用户导航回列表
  • 列表显示了突出显示喜欢"图标的水果

如何通知我在选择行之前所在的列表,单元格状态的变化(不喜欢现在喜欢).我如何通知其他列表(在另一个选项卡中)同样的事情?

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?

谢谢各位

编辑

我会尝试展示一个真实的样本!当你去应用商店搜索 GMAIL 时

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.

推荐答案

简单的方法是用数组水果创建一个单例类.例子:你有模型水果:

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

每当 1 个水果喜欢或不喜欢时,更改该水果的属性,并使用 NSNotification 将更改通知其他视图控制器.接收通知的视图控制器将访问单例类的水果列表.

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.

这篇关于IOS开发中View Controllers之间共享对象状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆