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];
有帮助吗?

解决方案

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).

其他提示

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top