gpt4 book ai didi

objective-c - 多个代表或通知中心

转载 作者:搜寻专家 更新时间:2023-10-30 20:25:58 26 4
gpt4 key购买 nike

让我解释一下。我有一个数据类,它只不过是 NSMutableArray 的一个实例。我添加了 currentItem 的属性。当我的应用程序启动时,会生成此类的一个实例,然后与多个 View Controller 共享。

当这些 View Controller 中的任何一个设置当前项时([myClass setCurrentItem:(MyItem*)item] 我想通知所有 View Controller 以便它们可以更新它们的 UI 等...

我对实现解决方案的最佳方式感到矛盾。我可以:

1.) 使用自定义协议(protocol),让我的类通过添加方法 addDelegate:(id)instance 跟踪委托(delegate)集合,将委托(delegate)集合保存在 NSMutableArray ivar 中,然后在设置 currentItem 时进行迭代和通信.

2.) 当设置 iVar 时,使用 NSNotification 中心进行通信。

就代表而言,调用顺序对我来说并不重要。

哪种方法更适合这种情况?在我看来,选项 #1 是更简洁的方法,但我对“多个代表”的搜索结果表明,当有多个代表时,我应该使用 NSNotification 中心,但背后没有太多理由。

你有什么看法,为什么?

最佳答案

我认为上面的评论总结了一些想法,但我只想补充几点:

When any of those view controllers sets the current item ([myClass setCurrentItem:(MyItem*)item] I want to notify all of the view controllers so that they can update their UI etc...

这意味着您正在更新所有 UIViewController,即使它们不可见。您没有说明您正在为哪个平台开发,但总的来说,我的目标是仅在绝对需要时更新 Controller (即,当它们对用户可见时)。在这种情况下,您可以选择将逻辑放入 viewWillAppear: 和/或 viewDidAppear: 来检查您的模型(即 NSMutableArray)和适本地更新 View 。

现在,是使用 NSNotifications 还是协议(protocol)方法和委托(delegate)是一个棘手的问题。我想有几点需要考虑:

  1. 您是否拥有或管理您的类(class)的单一对象?通常,这适用于委托(delegate) - 例如 UITableView
  2. 您是否要确保单个对象必须对事件实现方法 - 同样,协议(protocol)可以确保方法得到实现并使文档清晰。

否则通知非常方便。查看标准框架并从中获取指导​​,但要意识到其中很多只是一种判断。例如,查看 UITextField - 它使用 UITextFieldDelegate 协议(protocol),但也会创建通知。我确定有一个很好的理由,但可能需要花一些时间考虑一下......

编辑:如您所述,为了完整性:

2.) Use NSNotification center to do this communicating when iVar is set.

键值观察 (KVO) 允许您直接使用对象实例变量注册通知。

来自 iOS 5.1 文档:

Key-value observing is a mechanism that enables an object to be notified directly when a property of another object changes. Key-value observing (or KVO) can be an important factor in the cohesiveness of an application. It is a mode of communication between objects in applications designed in conformance with the Model-View-Controller design pattern. For example, you can use it to synchronize the state of model objects with objects in the view and controller layers. Typically, controller objects observe model objects, and views observe controller objects or model objects.

我会添加指向文档的链接,但目前没有我的书签。

关于objective-c - 多个代表或通知中心,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11624733/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com