objective-c - Objective-C 中的匿名委托(delegate)实现?

标签 objective-c delegates anonymous-class

是否可以在 Objective-C 中声明诸如委托(delegate)之类的匿名实现。我想我的术语是正确的,但这是一个 Java 示例:

myClass.addListener(new FancyInterfaceListener({
    void onListenerInterestingAction(Action a){
        ....interesting stuff here
    }
});

例如,要处理 UIActionSheet 调用,我必须在同一个类中声明另一个方法,如果我想向它传递数据,这似乎有点愚蠢,因为我必须将该数据存储为全局变量。下面是一个删除内容的示例,带有一个确认对话框,询问您是否确定:

-(void)deleteItem:(int)indexToDelete{
    UIActionSheet *confirm = [[UIActionSheet alloc] initWithTitle:@"Delete Item?" delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:@"Delete" otherButtonTitles:nil];
    [confirm showInView:self.view];
    [confirm release];
}

和同一个类中的 UIActionSheetDelegate:

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 0){
        [[Settings sharedSettings] removeItemAtIndex:/*need index variable here*/];
        [drinksTable reloadData];
    }
}

我希望能够做的是将其声明为内联,就像我在顶部的 java 示例中所做的那样。这可能吗?

最佳答案

目前在 Objective-C 中无法做到这一点。 Apple 已经发布了一些关于他们为该语言添加 block (实际上更像是 lambda 闭包而不是匿名类)的工作。您可能能够使用这些执行类似于匿名委托(delegate)的操作。

与此同时,大多数 Cocoa 程序员将委托(delegate)方法添加到委托(delegate)类的单独类别中。这有助于使代码更有条理。在您的示例的类的 .m 文件中,我将执行如下操作:

@interface MyClass (UIActionSheetDelegate)
- (void)actionSheet:(UIActionSheet*)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex;
@end

@implementation MyClass
//... normal stuff here
@end

@implementation MyClass (UIActionSheetDelegate)
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 0){
        [[Settings sharedSettings] removeItemAtIndex:/*need index variable here*/];
        [drinksTable reloadData];
    }
}
@end

Xcode在编辑器窗口中弹出的方法会将类别的声明和实现与主类分开。

关于objective-c - Objective-C 中的匿名委托(delegate)实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/766475/

相关文章:

Java,匿名内部类定义

ios - 当我设置约束时,为什么我的 UITableView 将自身报告为 600x600,或者 Storyboard 中的内容?

objective-c - 无论如何让(包装)NSTextField 在按下回车键时写一个回车?

objective-c - 释放@property(copy) 实例变量?

ios - 如何在 ViewController 之间传递 UIButton 的框架和原点

C# 如何避免多个开关(委托(delegate)?)

C# 删除事件处理程序

java - 能否以某种方式限定最终参数以解决与匿名类成员的命名冲突?

constructor - 如何在 TypeScript 中匿名类

objective-c - 如何以编程方式在 iOS 中按下 "dictate"键盘键(Objective-C)