问题描述
我看到这篇文章:
代理==控制器
代理和控制器这个词可以同义使用....
不清楚他在说什么,但我明白mvc比编程中的代表更好。
这两个类似吗?
他们真的在不同的层次上。
使用Delegate的类是一个Class(任何Class),它被设计为使得自定义行为可以由另一个对象提供,而不是通过子类化来提供。 >
eg 大多数Cocoa Apps都希望在应用程序启动时做一些自定义的操作(如果没有这样的话很无聊)。而不是要求每个Cocoa应用程序实现 NSApplication
的自定义子类,仅覆盖 -applicationWillFinishLaunching:
, NSApplication
被设计为如果您将委托
属性设置为有效对象,并且该对象具有 -applicationWillFinishLaunching :
方法将会调用它。
这样你可以使用任何你喜欢的类进行安装,你不必使其成为NSApplication的子类。
许多Cocoa类像这样工作,这意味着你几乎不必将它们子类化以添加自定义行为。在某些其他语言和框架中,您应该添加自定义行为的方式是通过子类化。想在java中定制按钮?只需创建一个扩展JComponent并实现MouseListener的新类,然后重写mouseClicked等。这不是Cocoa的方式。
一个控制器,正如你所知,是一个负责任的对象用于协调模型和视图。
如果您需要向模型对象或视图对象的实例添加自定义行为,例如,您可以有一个NSTableView对象,并且您希望在选择行时添加自定义行为 - 您可能已经有一个自定义的Controller对象,这通常是放置代码的完美的地方。只要设置TableView's.delegate = controller。我们可以看到,tableView有一个委托方法 - tableViewSelectionDidChange:
您不必创建NSTableView的子类。
我不认为这意味着一个代表和一个控制器是一样的。
I saw this article:
http://www.cimgf.com/2008/10/01/cocoa-touch-tutorial-iphone-application-example/
"Delegate == ControllerThe words delegate and controller can be used synonymously...."
I'm not sure what he is saying but I understand mvc better than I do delegates in programming.
Are the two similar?
They are really on different levels.
A Class that uses a Delegate is a Class (any Class) designed so that custom behaviour can be provided by another object instead of, say, by subclassing.
e.g. most Cocoa Apps will want to do something custom on app launch (pretty boring if they didn't). Instead of requiring every Cocoa App to implement a custom Subclass of NSApplication
just to override –applicationWillFinishLaunching:
, NSApplication
is designed so that if you set it's delegate
property to valid object, and that object has an –applicationWillFinishLaunching:
method it will call that.
That way you can use any Class you like for your setup, you don't have to make it a Subclass of NSApplication.
Many Cocoa Classes work like this, meaning you hardly ever have to subclass them to add custom behaviour. In some other languages and frameworks the way you are supposed to add your custom behaviour is by subclassing. Want a custom button in java? Just create a new Class that extends JComponent and implements MouseListener then override mouseClicked, etc. This is not the Cocoa way.
A controller, as you know, is an Object responsible for coordinating the Model and the View.
As it happens, if you need to add custom behaviour to an instance of a Model Object or a View Object - say for example you have an NSTableView object and you want to add custom behaviour when a row is selected - you probably already have a custom Controller object and this is often the perfect place to put the code. Just set the TableView's.delegate = controller. We can see here that tableView has a delegate method - tableViewSelectionDidChange:
You don't have to create a subclass of NSTableView.
I don't consider this to mean that a Delegate and a Controller are the same thing at all.
这篇关于是一个类似于mvc控制器的代理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!