代表目标c [英] Delegates in objective c

查看:133
本文介绍了代表目标c的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我应该告诉你对Objective C或C#的一点知识。当我的一个同事询问Objective C中是否有委托时,我想知道Objective-CI是否存在这样的概念猜测代理我们使用在iphone中编程不一样。#代表是函数指针对吗?这样的设施在使用多个视图时很好。我们在哪里可以找到信息

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??

推荐答案

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#中的代表是实现工件。有一个专门的委托关键字来声明委托类型并创建实际的委托实例。

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);

    ...
}

bit生锈,所以语法可能在这里,对不起;在现实生活中,可能会使用事件在像上面而不是原始委托的情况下)。基本上,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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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