views:

48

answers:

1

Is it possible to set the return type of a selector in objective-c to be the class itself?

For example, is it possible to do something like:

+ ([self class] *) selectorName;

So that given a super class such as:

@interface MyClass : NSObject {}
+ (MyClass *) instanceOfMyClass;
@end

@implementation MyClass 
+ (MyClass *) instanceOfMyClass {
  return [[[[self class] alloc] init] autorelease];
}
@end

The subclass does not need to cast the return value when doing things like:

@implementation MySubClass 
+ (MySubClass *) specialInstanceOfMySubClass {
  MySubClass *instance = [[self class] instanceOfMyClass];
  instance.special = YES;
  return instance;
}
@end

In other words, im trying to expose the fact that the static method returns an instance of the class or its subclass. Otherwise, the subclass needs to be aware of information not provided in the interface.

Thanks!

A: 

There is no such thing. There are basically two ways to type variables in Objective-C:

  • static: like you already did: ClassName *
  • anonymous: use the generic type id that can match any object

So in your case you could do a method declaration like this:

+ (id)instanceOfMyClass;

The convention is to return an instance of that class. Apple uses this convention in basically every class. If the result is different, you should write it in the documentation for this method. That's also the way Apple does this.

Another option would be to cast the result in you subclass' method.

MySubClass *instance = (MySubClass *)[[self class] instanceOfMyClass];
Max Seelemann
I wanted to avoid having to cast. Casting requires the subclass to have knowledge of the implementation of the super class; it's the same for using id (though with id it's less ambiguous). Casting bypasses strong typing.
jbenet
Actually *I* don't know of any language that supports what you were asking for. May well be lack of my knowledge. However, the `id`-solution seems pretty okay to me...
Max Seelemann
Hmm. Yeah, i guess id's good enough. And since it's id and not MyClass *, then the subclass knows it's probably [self class].
jbenet