2013-05-29 73 views
0

你好,感謝你的時間。我相當新IOS/Objective C動態選擇變量

我有我的viewcontroller頂部全局設置多個變量。

NSMutableArray * A; 
NSMutableArray * B; 
NSMutableArray * C; 

現在,當有人在tableview中選擇一個單元格時,我想使用該單元格的名稱來選擇一個全局變量。我發現了一些與viewcontrollers做這件事,但我也需要一些misc變量。我reffering到:

id myNewController = [[NSClassFromString(selected) alloc] init]; 
[[self navigationController] pushViewController:myNewController animated:YES]; 

因此,這將是這樣的:提前任何幫助

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { 
// Save text of the selected cell: 
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath]; 
stringVariable = cell.textLabel.text;// value=A,B or C 

// match string to array and load that array. 
??   

} 

謝謝,對不起,如果這已經被問,但我無法找到任何工作所以作爲最後的手段,我要求幫助:)

回答

1

您可能會更好地將數組作爲鍵存儲在字典中,而不是單個字段。例如:

NSDictionary* dictionary; 

dictionary = @{ 
    @"A": [[NSMutableArray alloc] init], 
    @"B": [[NSMutableArray alloc] init], 
    @"C": [[NSMutableArray alloc] init] 
}; 

然後在選擇你行,你可以通過鍵查找數組:

UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath]; 
NSString* key = cell.textLabel.text;// value=A,B or C 

NSMutableArray* array = dictionary[key]; 
.... 
+0

似乎是一個可行的解決方案。我見過之前,我只需要它簡化,所以我可以把握它。我會試着去實踐它,如果它符合我的期望,我會評價你。謝謝你的幫助bendytree :) – Anthem127

+0

這使我走上了正確的道路,唯一需要做的就是改變我初始化字典的方式。 我需要將現有數組添加到字典中,然後將它們傳遞給事件處理程序,如下所示: dictionary = [NSDictionary dictionaryWithObject:A forKey:@「A」]; 做了詭計fr我,謝謝! – Anthem127