25

是否可以在 Objective-C 中声明诸如 Delegates 之类的匿名实现。我认为我的术语是正确的,但这是一个 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 示例中所做的那样。这可能吗?

4

5 回答 5

17

目前在 Objective-C 中没有办法做到这一点。Apple 已经发布了一些关于向语言添加块(实际上更像 lambda 闭包而不是匿名类)的工作。您可能可以用这些做类似于匿名委托的事情。

同时,大多数 Cocoa 程序员将委托方法添加到委托类的单独类别中。这有助于使代码更有条理。在您示例中的类的 .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 在编辑器窗口中弹出的方法会将类别的声明和实现与主类分开。

于 2009-04-20T16:09:22.507 回答
4

Objective-C 没有像 Java 那样的匿名类的概念,所以你不能像在 Java 代码中那样创建一个“内联”类。

于 2009-04-20T00:22:26.247 回答
2

当我遇到这个问题时,我一直在寻找不同的东西,但是如果你搜索 UIALERTVIEW+BLOCKS,你会发现做内联 UIALERTVIEWs 的几个命中。这是我一直在使用的:ALERTVIEW w/blocks

于 2011-06-17T14:03:24.943 回答
1

我相信匿名类可以在Objective-C中实现,但这需要大量的NSProxy魔法和IMP疯狂。这是我目前的项目之一。

于 2009-12-01T00:03:14.320 回答
0

一个实现委托接口的类怎么样。在初始化时它会占用一个块。在委托定义中,它调用此块。

这允许多个 UIActionSheets 同时存在,而无需比较身份。

于 2012-04-26T21:08:59.763 回答