代码之家  ›  专栏  ›  技术社区  ›  rustyshelf

Objective-C中匿名委托的实现?

  •  24
  • rustyshelf  · 技术社区  · 17 年前

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

    5 回复  |  直到 17 年前
        1
  •  17
  •   Barry Wark    17 年前

    目前在Objective-C中无法实现这一点。苹果公司已经发表了一些关于向语言中添加块(实际上更像是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
    

        2
  •  4
  •   mipadi    17 年前

        3
  •  2
  •   KevinO    15 年前

    当我遇到这个问题时,我正在寻找一些不同的东西,但是如果你搜索UIALERTVIEW+块,你会发现一些用于内联UIALERTVIEW的点击率。这是我一直在使用的: ALERTVIEW w/blocks

        4
  •  1
  •   Jonathan Sterling    16 年前

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

        5
  •  0
  •   arithma    14 年前

    一个实现委托接口的类怎么样。