我確信這個問題必須在某個地方得到解答,但我正在努力尋找正確的答案。如何將數組的元素傳遞給可變參數函數?
在我的objective-c代碼中,我有一個未知數字字符串的NSArray,我想將它的元素傳遞給一個可變初始化方法,在這種情況下,它的... UIActionSheet constructer中的'otherButtonTitles'列表。這怎麼能實現?
在此先感謝
我確信這個問題必須在某個地方得到解答,但我正在努力尋找正確的答案。如何將數組的元素傳遞給可變參數函數?
在我的objective-c代碼中,我有一個未知數字字符串的NSArray,我想將它的元素傳遞給一個可變初始化方法,在這種情況下,它的... UIActionSheet constructer中的'otherButtonTitles'列表。這怎麼能實現?
在此先感謝
我認爲你需要數組的第一個元素傳遞給構造函數,然後通過剩餘的元素使用addButtonWithTitle方法循環,並增加他們:
UIActionSheet *mySheet = [[UIActionSheet alloc] initWithTitle:title delegate:delegate cancelButtonTitle:cancelButtonTitle destructiveButtonTitle:destructiveButtonTitle otherButtonTitles:[myOtherButtons objectAtIndex:0],nil];
NSMutableArray *otherbuttons = myOtherButtons;
[otherButtons removeObjectAtIndex:0];
NSEnumerator *enumerator = [otherButtons objectEnumerator];
id anObject;
while (title = [enumerator nextObject]) {
[mySheet addButtonWithTitle:title];
}
沒有一個通用的方法來做到這一點,但是對於UIActionSheet來說,你不需要使用那個構造函數。
UIActionSheet *sheet = [[UIActionSheet alloc] init];
// set properties
sheet.title = @"Title!";
// add buttons
for (NSString *buttonTitle in otherButtonTitles) {
[sheet addButtonWithTitle:buttonTitle];
}
sheet.cancelButtonIndex =
[sheet addButtonWithTitle:@"Cancel"];
UIAlertView可以用類似的方式初始化。
我想我期待稍微更優雅一些,謝謝,雖然,工作正常。 – Elric 2010-11-14 20:26:03