Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C equivalent to Java's anonymous classes in class methods

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;
}

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.

like image 646
hpique Avatar asked Sep 22 '10 14:09

hpique


People also ask

How do you create an object of an anonymous class?

Object = new Example() { public void display() { System. out. println("Anonymous class overrides the method display()."); } }; Here, an object of the anonymous class is created dynamically when we need to override the display() method.

Can anonymous class have multiple methods?

Because the EventHandler<ActionEvent> interface contains only one method, you can use a lambda expression instead of an anonymous class expression. See the section Lambda Expressions for more information. Anonymous classes are ideal for implementing an interface that contains two or more methods.

Does C# have anonymous classes?

In C#, an anonymous type is a type (class) without any name that can contain public read-only properties only. It cannot contain other members, such as fields, methods, events, etc. You create an anonymous type using the new operator with an object initializer syntax.


2 Answers

As JeremyP has rightly said, There are no anonymous classes in Objective C like there are in Java.

But in Java, anonymous classes are mostly used to implement single method interface or what we also call as a functional interface.

We do it to avoid having to implement the interface** in a class **just for one method implementation which is most commonly used for Listeners, Observers and event handlers.

This is mostly done because of **lack of anonymous first class functions in Java (prior to version 8 and project lambda).

Objective C has something called as blocks, where you can directly pass a block which contains the implementation of that single method rather than an empty class wrapping it up.

Example:

A use of Anonymous Class in 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
                              }
                         });

In Objective 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
                                            }];
like image 167
Amogh Talpallikar Avatar answered Sep 22 '22 15:09

Amogh Talpallikar


There are currently no anonymous classes in Objective-C.

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.

like image 38
JeremyP Avatar answered Sep 21 '22 15:09

JeremyP