Anonymous delegate implementation in Objective-C?

让人想犯罪 __ 提交于 2019-11-30 02:03:29

There is no way to do this in Objective-C currently. Apple has published some work on their efforts to add blocks (really more like lambda closures than anonymous classes) to the language. You would likely be able to do something similar to the anonymous delegate with those.

In the mean time, most Cocoa programmers add the delegate methods to a separate category on the delegate class. This helps to keep the code more organized. In the .m file for the class in your example, I would do something like this:

@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's method popup in the editor window will separate the category's declaration and implementation from the main class'.

Objective-C doesn't have a notion of anonymous classes like Java's, so you can't create a class "inline" like in the Java code.

I was looking for something different when I came across this but if you do a search for UIALERTVIEW+BLOCKS you will find several hits for doing inline UIALERTVIEWs. This is the one I've been using: ALERTVIEW w/blocks

I believe that anonymous classes can be implemented in Objective-C, but it will take a lot of NSProxy magic and IMP madness. This is one of my current projects.

How about a class implementing the delegate interface. On initialization it would take a block. In the delegate definition it calls this block.

This allows multiple UIActionSheets to exist simultaneously without having to compare on identity.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!