Question

How does one detect the calling class from within a static method such that if the class is subclassed the subclass is detected? (See comment inside MakeInstance)

@interface Widget : NSObject
+ (id) MakeInstance;
@end

@implementation Widget
+ (id) MakeInstance{
    Class klass = //How do I get this?
    id instance = [[klass alloc] init];
    return instance;
}
@end

@interface UberWidget : Widget
//stuff
@end

@implementation UberWidget
//Stuff that does not involve re-defining MakeInstance
@end

//Somewhere in the program
UberWidget* my_widget = [UberWidget MakeInstance];
Was it helpful?

Solution

I believe the appropriate solution for what you are trying to accomplish is this:

+ (id) MakeInstance{
    id instance = [[self alloc] init];
    return instance;
}

And as Cyrille points out, it should probably return [instance autorelease] if you want to follow convention (and aren't using ARC).

OTHER TIPS

UIAdam's solution is perfectly fine for your case. Although if you want to detect, more specifically, from which class is you method called, use [self class] on objects, or simply self for classes.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top