0

在 C# 中,您可以创建委托方法,将其分配给变量或将其传递给方法,就好像它是变量一样。例如:

public delegate int Lookup(String s);
//...
public static int Evaluate(String exp, Lookup variableEvaluator)
{
//...
}

我听说在 C 中你可以创建一个指向任何方法的指针,然后将该指针传递给一个方法。谁能给我一个在Objective-C中这样做的简单例子?当然,我可以使用单个方法创建一个对象并将该对象传递给一个方法。但我很好奇是否有一种类似于 C# 或 C 的方法。

4

3 回答 3

2

很多方法。

一:好的。使用块(闭包,lambda演算,不管你怎么称呼它):

typedef void (^MyCallback)();

- (void)callTheCallback:(MyCallback)blockToInvoke
{
    blockToInvoke();
}

MyCallback cb = ^{
    NSLog(@"I was called! :D");
};
[self callTheCallback:cb];

二:坏。获取指向方法函数本身的指针并调用它。(警告:如果你使用这种方法,我会起诉你。)

- (void)callTheCallback:(IMP)funcPtrToCall withObject:(id)obj selector:(SEL)sel
{
     funcPtrToCall(obj, sel);
}

- (void)someCallbackMethod
{
    NSLog(@"I was called! :D");
}

IMP implemt = [[self class] instanceMethodForSelector:@selector(someCallbackMethod)];
[self callTheCallback:implemt withObject:self selector:@selector(someCallbackMethod)];

三:丑。使用委托:

- (void)delegateMethodOfSomeObject:(SomeObject *)obj
{
    NSLog(@"I was called! :D");
}

SomeObject *obj = [[SomeObject alloc] init];
obj.delegate = self;
[obj makeThisObjectSomehowCallItsDelegateThatIsCurrentlySelf];
于 2012-10-12T20:42:38.183 回答
1

两个快速的想法浮现在脑海。

简短的答案称为“块”,但它可能低于您所需要的推荐级别。

“更清洁”的解决方案(阅读:更高级别)是传递两个参数:对象(称为“目标”)和选择器(称为“动作”)。这是 Objective-C 中非常常见的模式,所以我只演示这个模式。如果您对积木的想法感兴趣,请查看此文档

本质上,对象应该作为 id 传递,选择器作为 SEL 传递,为此我们有方便的 @selector() 构造:

-(void) doThingWithTarget:(id) targetObj action:(SEL) actionSel {
  if([targetObj respondsToSelector:actionSel]) {
    [targetObj performSelector:actionSel withObject:self];
  }
}

// ...
[thatOtherObject doThingWithTarget:self action:@selector(myMethod:)];

// ... where

-(void) myMethod:(id) sender {
  // sender is the calling object, or should be by contract.
}
于 2012-10-12T20:39:09.023 回答
0

Objective C 使用选择器。http://developer.apple.com/library/ios/#documentation/cocoa/conceptual/objectivec/Chapters/ocSelectors.html

于 2012-10-12T20:37:52.683 回答