问题描述
首先我应该告诉你,我对 Objective C 或 C# 知之甚少.所以当我的一位同事问我在 Objective C 中是否有类似委托的东西时,我想知道在 Objective-CI 中是否存在这样的概念,猜猜委托我们在iphone编程中使用的不一样.C#委托是函数指针对吗?在处理多个视图时拥有这样的设施会很好.我在哪里可以找到信息??
First I should tell you that ive little knowledge of Objective C or C#.So when one of my collegues asked me whether there is anything like delegates in Objective C,I wondered if such a concept existed in Objective-C.I guess the delegates we use in iphone programing are not the same.C# delegates are function pointers right? Such a facility would be nice to have while working with multiple views.Where can i find info??
推荐答案
Objective-C 中的委托只是一个概念,而不是某种实现工件(如在 C# 中).Objective-C 中的委托(更好的是:Cocoa)基本上是一个对象,任何使用它作为发生某些事件的委托"的人都会通知它.也可能要求代表代表宿主对象执行某些任务.委托需要实现的接口通常由协议形式化.
Delegates in Objective-C are merely a concept, not some kind of implementation artifact (like in C#). A delegate in Objective-C (better: Cocoa) is basically an object, which is notified by whoever uses it as its "delegate" of certain events occuring. Delegates may also be asked to perform certain tasks on behalf of the host object. The interface a delegate is required to implement is often formalized by a protocol.
@protocol ActionDelegate
- (void) actionDidStart: (id) aSender;
- (void) actionDidEnd: (id) aSender;
@end
@interface Action: NSObject {
id<ActionDelegate> delegate;
}
@property (nonatomic,assign) id<ActionDelegate> delegate;
@end
另一方面,C# 中的委托是一个实现工件.有一个专用的 delegate
关键字来声明委托类型并创建实际的委托实例.
Delegates in C#, on the other hand, are an implementation artifact. There is a dedicated delegate
keyword to declare delegate types and to create actual delegate instances.
class Action {
delegate void ActionDidStartDelegate(Action sender);
delegate void ActionDidEndDelegate(Action sender);
...
}
(我的 C# 有点生疏,所以这里的语法可能不对,抱歉;在现实生活中,可能会在上述情况下使用事件而不是原始委托).基本上,C# 委托类似于 Python 方法对象.
(my C# is a bit rusty, so the syntax may be off here, sorry; and in real life, one would probably use events in situations like the above rather than raw delegates). Basically, a C# delegate is akin to a Python method object.
您也许可以使用 Objective-C 的新代码块功能来模拟委托.尚未使用此功能(尚未),我无法对此发表评论.获得类似结果的另一种方法是使用普通函数指针.
You might be able to use the new code block feature of Objective-C to emulate delegates. Not having used this feature (yet), I cannot comment on this. Another way to get something like that would be to use plain function pointers.
typedef void (*callback_function)();
- (void) doSomethingWithCallback: (callback_function) func {
...
func();
}
当然,您总是可以使用 Cocoa 本身经常使用的方法:使用对象和关联的方法选择器:
And of course, you can always use the method often employed by Cocoa itself: use an object and an associated method selector:
- (void) doSomethingWhenDonePerform: (SEL)aSelector onObject: (id) aReceiver {
...
[aReceiver perform: aSelector];
}
这篇关于目标 c 中的代表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!