2013-12-09 22 views
0

如何在objective-c中創建一個方法,我可以每次運行帶有不同參數的方法。例如,我希望能夠做這樣的事情:如何使用objective-c中的參數運行方法?

int thisMethod (int thisInt; NSString *thisString) { 
    int anotherInt = thisInt+2; 
    self.thisLabel.stringValue = thisString; 
    return 0; 
} 

所以在這個代碼,我想與在該方法使用兩個參數運行thisMethod。 即:

thisMethod(10; @"String"); 

我需要使用這樣的結構:

- (int) thisMethod:(id)sender{ 
    //code here 
} 

如果是這樣,我該如何使用這些參數?

+5

閱讀[與Objective-C編程](https://developer.apple.com/library/mac/documentation/cocoa/conceptual/ProgrammingWithObjectiveC/Introduction /Introduction.html) – DrummerB

+0

是的,你最好閱讀一些教程。對於Objective-C來說,除了理解時髦的調用語法之外還有很多。 –

+1

順便說一句 - 你的第一個'thisMethod'不是一個方法,它是一個函數。 – rmaddy

回答

0
- (int)thisMethodWithInt:(int)thisInt andString:(NSString *)thisString { 
    int anotherInt = thisInt+2; 
    self.thisLabel.stringValue = thisString; 
    return 0; 
} 

調用方法則是這樣的:

[self thisMethodWithInt:3 andString:@"My Super String"]; 

你所描述的交流功能,而不是一個Objective-C的一個..

+0

這也需要在'thisLabel'聲明爲'@ property' – Ralfonso

+0

這是正確的..我不知道他的設置......當然你也可以傳遞一個UI/NSLabel作爲參數如果你沒有那個 – lukaswelte

0

你將不得不通過標籤也是對象,因爲自我在C函數中沒有意義。在Objective-C是傳遞給每一個方法隱藏的參數,但在C函數,你必須自己通過它(使用逗號,而不是分號):

int thisMethod (int thisInt, NSString *thisString, id object) { 
    int anotherInt = thisInt+2; 
    object.thisLabel.stringValue = thisString; 
    return 0; 
} 

你可能要明確設置鍵入雖然,而不是使用id,或編譯器會抱怨。

同樣,使用逗號分隔參數:

thisMethod(10, @"String", self); 
相關問題