2013-10-01 26 views
2

我有一個需要從課內外調用的函數。下一個代碼工作正常,但我想知道,有沒有辦法只有一個lowerKeyboard方法,而不是兩種方法 - 和+? 如果我將只保留+方法試圖從類例子和Class方法相同。可能?

內部調用的方法從類的內部時,我會得到一個錯誤unrecognized selector sent to instance

-(void)someOtherMethod 
{ 
    UIBarButtonItem *infoButtonItem=[[UIBarButtonItem alloc]initWithTitle:@"Done" style:UIBarButtonItemStyleDone target:self action:@selector(lowerKeyboard)]; 
} 

從類的外部:

[myClass lowerKeyboard]; 

MyClass的:

-(void)lowerKeyboard 
{ 
    //do something 

} 

+(void)lowerKeyboard 
{ 
     //do the exact same thing 
} 
+0

可能重複的[類和實例方法之間的區別是什麼?](http://stackoverflow.com/questions/1053592/what-is-the-difference-between-class-and-instance-methods) –

+0

@DavidCaunt你看起來像破壞了壞!我不是在尋求差異,我知道差異。我的問題是如何結合這兩者。 – Segev

+0

不,他長得像我! –

回答

3

假設你有以下幾點:

- (void)doFoo 
{ 
    NSLog(@"Foo"); 
} 

+ (void)doFoo 
{ 
    NSLog(@"Foo"); 
} 

您可以重構這個要麼不喜歡這兩種實現這樣:

- (void)doFoo 
{ 
    [[self class] doFoo]; 
} 

+ (void)doFoo 
{ 
    NSLog(@"Do Foo!"); 
} 

然而,值得指出的是,有兩個類似的命名方法,這樣正在尋求麻煩。爲了避免混淆,刪除兩個接口中的一個會更好(尤其是因爲您只需要一個實現副本!)。

糟糕的建議如下 - 沒有真正做到這一點,除非你真的知道如何惹運行時(我不知道。)

從技術上講,你可以複製一個類的實現和實施情況通過編輯運行時,像這樣:

// Set this to the desired class: 
Class theClass = nil; 
IMP classImplementation = class_getImplementation(class_getClassMethod(theClass, @selector(doFoo))); 
class_replaceMethod(theClass, @selector(doFoo), classImplementation, NULL) 

這應該確保調用+ [theClass描述doFoo]電話完全一樣實現與調用 - [theClass描述doFoo。它將原始實例實現從類的實現堆棧中徹底刪除(因此請謹慎處理)。然而,我想不出有任何真正合法的情況,所以請用少許鹽來對待!

+0

如何將選擇器設置爲該方法?我應該將它設置爲另一種方法,該方法應該調用[[self class] doFoo]; ?如果我將選擇器設置爲doFoo,我仍然會將'無法識別的選擇器發送到實例' – Segev

+0

@Sha大衛的建議是,您應該有實例方法,正是爲了避免這種「無法識別的選擇器」。而且我喜歡實例方法調用類方法的方法比第一種方法(複製代碼)或者yikes(方法的運行時替換)要好得多。 – Rob

+1

@DavidDoyle +1,但是,沒有冒犯,我希望你停止提供'class_replaceMethod'方法。學術上有意思的是,你可以做到這一點,但是,哇,我同意,真是個壞主意!大聲笑 – Rob

0
-(void)lowerKeyboard 
{ 
    //this can be called on class instance 

    //UIBarButtonItem *infoButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"Done" style:UIBarButtonItemStyleDone target:self action:@selector(lowerKeyboard)]; 
    //[infoButtonItem lowerKeyboard]; 
} 

+(void)lowerKeyboard 
{ 
    //this can be used as class static method 
    //you cannot use any class properties here or "self" 

    //[UIBarButtonItem lowerKeyboard]; 
} 
相關問題