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!
There is no such thing. There are basically two ways to type variables in Objective-C:
ClassName *idthat can match any objectSo in your case you could do a method declaration like this:
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.