How to detect calling class in objective c static method
-
12-06-2021 - |
문제
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.
제휴하지 않습니다 StackOverflow