正如JeremyP所说,Objective C中没有像Java那样的匿名类。
但在Java中,匿名类主要用于实现单个方法接口或我们也称之为功能接口。
我们这样做是为了避免在一个类**中实现接口**,而该方法实现最常用于侦听器,观察者和事件处理程序。
这主要是因为 Java 中缺少匿名一等函数(在版本 8 和 lambda 项目之前)。
Objective C有一个叫做块的东西,你可以直接传递一个包含该单个方法实现的块,而不是一个空的类来包装它。
例:
匿名类在 Java 中的使用
//Functional interface
interface SomethingHandler
{
void handle(Object argument);
}
//a method that accepts the handler in some other class
class SomeOtherClass
{
void doSomethingWithCompletionHandler(SomethingHandler h){
// do the work that may consume some time in a separate thread may be.
// when work is done call the handler with the result which could be any object
h.handler(result);
};
}
// Somewhere else in some other class, in some other code
// passing the handler after instantiating someObj as an object of SomeOtherClass which can use the handler as needed
SomeOtherClass someObj = new SomeOtherClass();
someObj.doSomethingWithCompletionHandler( new SomethingHandler()
{
void handle(Object argument)
{
// handle the event using the argument
}
});
在目标C中
// declare the handler block
typedef void (^SomethingHandler)(id argument){}
// this interface is different than Java interface which are similar to Protocols
@interface SomeOtherClass
-(void)doSomethingWithCompletionHandler:(SomethingHandler)h;
@end
@implementation SomeOtherClass
-(void)doSomethingWithCompletionHandler:(SomethingHandler)h
{
// do the work that may consume some time in a separate thread may be.
// when work is done call the handler with the result which could be any object
h(result);
}
@end
// passing the handler after instantiating someObj as an object of SomeOtherClass which can use the handler as needed
SomeOtherClass* someObj = [[SomeOtherClass alloc] init]; // ARC :)
[someObj doSomethingWithCompletionHandler:^(id argument)
{
// handle the event using the argument
}];