views:

68

answers:

1

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.

+2  A: 

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.

JeremyP
Thanks JeremyP! So basically in this case I could define an ad-hoc class in the implementation file, create an instance in the class message and assign it as delegate. Would that be correct?
hgpc
That's probably the right way to do it in this situation.
JeremyP