2012-08-24 86 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