2012-08-24 81 views
1

我很抱歉,我是新來的IOS,我不能找出解決這個問題字典檢索關鍵IOS

這只是一個初學者餐廳的菜單

有包含項的tableview和價格,當我點擊一個項目時,它會顯示另一個視圖,用戶必須輸入數量並單擊完成按鈕,因此當用戶點擊完成時,我想將數量乘以價格,我如何檢索該特定價格並請將其與文本字段中的數量用戶輸入相乘。

這裏是我的代碼

我已經叫

NSDictionary *dict; 

我viewDidLoad方法

dict=[[NSDictionaryalloc]initWithObjectsAndKeys: 
@"TomatoSoup",@"20.00",@"VegManchowSoup",@"12.00",nil]; 
NSLog(@"%@",dict); 
[super viewDidLoad]; 

我已經在表視圖中顯示該內容菜單頭文件中聲明的NSDictionary

- (NSInteger)tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section{ 
return [[dict allKeys]count]; 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ 
static NSString *CellIdentifier = @"Cell"; 

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
if (cell == nil) { 
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease]; 
} 

NSArray *sortedkeys=[[dict allKeys]sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)]; 
NSString *key=[sortedkeys objectAtIndex:indexPath.row]; 
NSString *value=[dict objectForKey:key]; 
cell.textLabel.text=value; 
cell.detailTextLabel.text=key; 
return cell; 
} 

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath{ 
if(indexPath.row==0){ 

VegQuantity *vegetarian1 = [[VegQuantity alloc] initWithNibName:@"VegQuantity" bundle:nil]; 
vegetarian1.m_SelectedIndexPath=indexPath.row; 
vegetarian1.pass=dict; 
[self presentModalViewController:vegetarian1 animated:YES]; 
} 
if(indexPath.row==1){ 

VegQuantity *vegetarian1 = [[VegQuantity alloc] initWithNibName:@"VegQuantity" bundle:nil]; 
vegetarian1.m_SelectedIndexPath=indexPath.row; 
[self presentModalViewController:vegetarian1 animated:YES]; 
} 
} 

VegQuantity.h 有一個視圖有一個文本框和一個按鈕說完成,現在當我點擊完成按鈕時,我需要檢索該特定湯的值,並將其與輸入的數量相乘。 我的問題是我該如何檢索該特定鍵的價格(價值)並將其與數量相乘。

回答

0

通過使用從字典中檢索值。

[dict objectForKey:@"someDummyKey"]; 

但說實話。你應該使用NSMutableArray作爲你的UITableView數據源而不是NSDictionary。

+0

如果我使用NSMutableArray我如何檢索特定湯的特定價格 – ipack26

+0

您將不得不爲每道菜製作一本詞典。包含鍵值對和鍵名和相應的值。 然後在'didSelectRowAtIndexPath'中,您只需將包含在數組中的字典傳遞給您的veggi-class。您將通過使用'indexPath.row'知道哪個數組。在Veggi-Class內部,您可以訪問正確的培養皿並使用數據。 – Maverick1st

+0

您只需訪問textfield.text即可獲得文本字段的值。您不應該忘記從字典和文本字段中包含的字符串中創建浮點值。否則你的乘法會失敗。 :) – Maverick1st

2
dict=[[NSDictionary alloc]initWithObjectsAndKeys: 
        @"TomatoSoup",@"20.00",@"VegManchowSoup",@"12.00",nil]; 

的方法是initWithObjectsAndKeys,這意味着首先是對象,然後鍵,(標號爲「20.00」,對象 - 「西紅柿湯」) - 在你的情況下,它是相反的。二,而不是有一個NSString的價格(我想它是價格或數量)使用NSNumber - [NSNumber numberWithFloat:20.0f]。

然後,讓你的VegQuantity視圖控制器(順便說一句這是好主意,把它VegQuantityViewController,爲了保持命名約定)2個屬性:

@property (nonatomic, strong) NSString *itemName; //Use strong if using ARC, otherwise retain 
@property (nonatomic, strong) NSNumber *price; 

,並通過這些值到視圖控制器,你前戲它。然後在裏面你可以隨心所欲地做任何事情。 P.S.使用屬性來操縱實例變量的值是一種很好的做法。

+0

謝謝,我想通了.. – ipack26