Objective-C / Cocoa:代理和控制器的正确设计 [英] Objective-C/Cocoa: Proper design for delegates and controllers
问题描述
请考虑以下常见情况:
您在Cocoa应用程序中有一些 MainView
,它由 MainViewController
控制。您的 MainView
包含一些控件,例如 UILabel infoLabel
。您还有一个委托 MyDelegate
类,它接收某种类型的事件。
You have some MainView
in your Cocoa application, loaded from a NIB, which is controlled by a MainViewController
. Your MainView
contains some controls, such as a UILabel infoLabel
. You also have a delegate MyDelegate
class which receives some sort of event.
MyDelegate
接收其事件, infoLabel
已适当更新。但是,问题是 MyDelegate
没有引用 MainView
或 MainViewController
You would like to make sure that when MyDelegate
receives its event, the infoLabel
is updated appropriately. However, the problem is that MyDelegate
does not have a reference to the MainView
or the MainViewController
and does not know about the label.
一个解决方案是传递 MainViewController
引用委托对象,但这感觉是错误的,因为你可能会发现自己处于不受欢迎的情况,其中对象有对方的引用。
One solution is to pass a MainViewController
reference to the delegate object, but this feels wrong because you might find yourself in the undesirable situation where the object has each other's references.
什么是正确的设计来解决这个问题?
What is the proper design to solve this problem?
推荐答案
在一个未命名的开发人员论坛中,有人写道:
In an unnamed developer forum, someone writes:
所以,为了做一个长的故事,我决定我将开始使用NSNotifications。人们一直在关注的斯坦福课程由两名苹果工程师教授。他们刚刚明确表示不使用应用程序委托或全局变量,并且说要使用NSNotifications,委托和KV观察。
So, to make a long story short, I have decided that I will start making use of NSNotifications. The Stanford course online that people have been following is taught by two Apple engineers. They have just now unequivocally said NOT to use the app delegate or global variables, and have said to use NSNotifications, delegates, and K-V observing.
如果这是苹果工程师说,我将朝着这个方向前进。
If that is what the Apple engineers say, I am going to move in that direction.
NSNotifications非常巧妙,因为它们不会真正干扰封装。侦听器只侦听通知和一个对象 - 我不认为它必须知道或关心谁发送它。
The NSNotifications are pretty ingenious in that they don't really interfere with encapsulation that much. The listener only listens for the notification and an object - I don't think it has to know or care who sent it.
所以在你的例子中,我会考虑有委托发布标签已更改的通知,或更好地让控制器在可能的情况下观察该属性。
So in your example I would consider having the delegate post a notification that the label had changed, or better yet have the controller observe that property if possible.
这篇关于Objective-C / Cocoa:代理和控制器的正确设计的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!