Objective-C等同于java方法中的匿名类 [英] Objective-C equivalent to Java's anonymous classes in class methods

查看:258
本文介绍了Objective-C等同于java方法中的匿名类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to set the delegate of an object inside a class method in Objective-C. Pseudo-code:

+ (ClassWithDelegate*) myStaticMethod {
    if (myObject == nil) {
        myObject = [[ClassWithDelegate alloc] init];
        // myObject.delegate = ?
    }
    return myObject;
}

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

In Java I would simply create an anonymous class that implemented the delegate protocol. How can I do something similar in Objective-C?

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

Basically I would like to avoid creating a separate class (and files) to implement a simple delegate protocol.

推荐答案

目标C中目前没有匿名类。

There are currently no anonymous classes in Objective-C.

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

Often you can use an already existing object. For instance, for an NSTableViewDataSource, you can implement the methods in the document or view controller and pass that as the delegate.

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

Or you can have the object itself implement the protocol and make it its own delegate in the default case.

或者发送委托消息的方法可以检查一个零代理,并在这种情况下做一些明智的事情。

Or the methods that send the delegate messages can check for a nil delegate and do something sensible in that situation.

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

Or you can declare and define a class inside the implementation file you are creating the object that needs a delegate.

这篇关于Objective-C等同于java方法中的匿名类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆