首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Objective-C等同于类方法中Java的匿名类

Objective-C等同于类方法中Java的匿名类
EN

Stack Overflow用户
提问于 2010-09-22 22:39:04
回答 3查看 10.5K关注 0票数 18

我想在Objective-C中的类方法中设置一个对象的委托。伪代码:

代码语言:javascript
复制
+ (ClassWithDelegate*) myStaticMethod {
    if (myObject == nil) {
        myObject = [[ClassWithDelegate alloc] init];
        // myObject.delegate = ?
    }
    return myObject;
}

在Java中,我只需创建一个实现委托协议的匿名类。我如何在Objective-C中做类似的事情?

基本上,我希望避免创建单独的类(和文件)来实现简单的委托协议。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2010-09-22 23:31:25

Objective-C中当前没有匿名类。

通常,您可以使用已经存在的对象。例如,对于NSTableViewDataSource,您可以在文档或视图控制器中实现方法,并将其作为委托传递。

或者,您可以让对象本身实现协议,并在默认情况下使其成为自己的委托。

或者,发送委托消息的方法可以检查nil委托,并在这种情况下执行一些合理的操作。

或者,您可以在创建需要委托的对象的实现文件中声明和定义一个类。

票数 16
EN

Stack Overflow用户

发布于 2013-07-16 19:11:36

正如JeremyP所说的那样,Objective C中没有像Java语言那样的匿名类。

但在Java中,匿名类主要用于实现单个方法接口或我们也称为函数接口的接口。

我们这样做是为了避免只为一个方法实现**在一个类**中实现接口,该方法最常用于侦听器、观察者和事件处理程序。

这主要是因为** Java中缺少匿名第一类函数(在版本8和项目lambda之前)。

目标C有一种叫做块的东西,在这里你可以直接传递一个包含单个方法的实现的块,而不是一个包装它的空类。

示例:

Java中匿名类的使用

代码语言:javascript
复制
//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
                              }
                         });

Objective C中的

代码语言:javascript
复制
// 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
                                            }];
票数 20
EN

Stack Overflow用户

发布于 2015-10-13 15:40:39

匿名类可以通过库来实现。几个月前,我在obj-c分支上工作,以改进旧的实现(与作者讨论),并添加我自己的机制,而不需要任何MMMutableMethods -c运行时操作。

https://github.com/k06a/MMMutableMethods

A.第一种机制在obj-c运行时类创建上起作用:

代码语言:javascript
复制
MM_CREATE(MM_REUSE,^(Class class){
    [class addMethod:@selector(onResultWithId:)
        fromProtocol:@protocol(AMCommandCallback)
            blockImp:^(id this,id res){
                NSLog(@"onResultWithId: %@",res);
            }];
    [class addMethod:@selector(onErrorWithJavaLangException:)
        fromProtocol:@protocol(AMCommandCallback)
            blockImp:^(id this,JavaLangException *e){
                NSLog(@"onErrorWithJavaLangException: %@",e);
            }];
})

B.第二种机制适用于简单的消息转发实现:

代码语言:javascript
复制
MM_ANON(^(MMAnonymousClass *anon){
    [anon addMethod:@selector(onResultWithId:)
       fromProtocol:@protocol(AMCommandCallback)
           blockImp:^(id this,id res){
               NSLog(@"onResultWithId: %@",res);
           }];
    [anon addMethod:@selector(onErrorWithJavaLangException:)
       fromProtocol:@protocol(AMCommandCallback)
           blockImp:^(id this,JavaLangException *e){
               NSLog(@"onErrorWithJavaLangException: %@",e);
           }];
})

第一个是在运行时创建新的obc-j类,它允许您使用MM_CREATE(MM_REUSE, *)创建类MM_CREATE_CLASS(MM_REUSE, *)和直接实例。默认情况下,类只在第一次执行时创建并重用,但您可以通过调用MM_CREATE_CLASS_ALWAYS(*)MM_CREATE_ALWAYS(*)来避免重用。

第二种机制不会创建任何运行时实例,只需记住选择器的块并将方法调用转发给它们。

我更喜欢第二种方式,不要在运行时创建太多的类。我觉得它更安全,功能也足够强大。

要使用这个库,只需:

代码语言:javascript
复制
pod 'MMMutableMethods', :git => 'https://github.com/k06a/MMMutableMethods'
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3770359

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档