2012-06-01 46 views
0

如何從靜態方法內檢測調用類,以便如果類是子類,則檢測到子類? (見裏面MakeInstance評論)如何檢測目標c靜態方法中的調用類

@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]; 
+1

Objective-C中沒有靜態方法。相反,有一些類方法,例如您在示例中顯示的方法。請注意,方法名稱應以小寫字母開頭,例如'makeInstance'而不是'MakeInstance'。 – jlehr

+1

請注意,這是Objective-C與Java和C++之間的重要區別之一 - 在Java和C++中,不可能做到這一點 – newacct

+0

@jlehr感謝您的額外信息。 **在我工作的地方,大寫方法名稱是工廠方法的風格約定。我會轉達你的關注;) – Brooks

回答

3

我相信,你所要完成的就是這個合適的解決方案:

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

正如西里爾指出,它可能應該返回[instance autorelease],如果你想遵循約定(並且不使用ARC)。

+0

這應該做到這一點,假設你添加一個'autorelease'到你的初始化器。 – Cyrille

2

對於你的情況,UIAdam的解決方案非常好。儘管如果您想要更具體地檢測您調用哪種類的方法,請在對象上使用[self class],或者在類上使用self