0

我正在制作一个卡路里计数器,并创建了一个 UIAlertView,它为我提供了食物清单。我做了一个NSMutableDictionary包含食物和卡路里的:

@implementation FoodDatabase

-(id)init 
{    
  self = [super init];
  if(self) 
  {
    food= [[NSMutableDictionary alloc] init];
    [food setObject:@"111" forKey:@"Rice"];       
  }
  return self;
}


-(NSString *) foodList: (NSString *) foodItem 
{
    for(NSString *key in [food allKeys]) 
    {        
        if([foodItem isEqual: key]) 
        {
            NSLog(@"%@",foodItem);
            return [food objectForKey:foodItem];
        }
    }
 }


@end

在另一堂课中,我创建了一个UIAlertView提供食物清单的列表。这是商品 Rice 的代码片段:

NSString *buttonTitle = [alertView buttonTitleAtIndex:buttonIndex];
if([buttonTitle isEqualToString:@"Rice"])
{        
    NSString *xyz = [foodData foodList: @"Rice"];
    food_calorie = ([xyz floatValue]);

    UIAlertView *rice_alert=[[UIAlertView alloc] initWithTitle:@"Enter quantity of rice consumed" message:@"100 gms = 111 calories" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Ok", nil];

    [rice_alert addTextFieldWithValue:@"" label:@"Enter quantity in gms"];

    RiceText = [rice_alert textFieldAtIndex:0];
    RiceText.keyboardType = UIKeyboardTypeNumberPad;
    RiceText.clearsOnBeginEditing = YES;
    RiceText.clearButtonMode = UITextFieldViewModeWhileEditing;
    RiceText.keyboardAppearance = UIKeyboardAppearanceAlert;
    rice_alert.tag = RiceAlertView;

    [rice_alert show];
    [rice_alert release];

}

_RiceText_我使用用户在 中输入的值和_object_为特定键(在本例中为大米)返回的值来计算总卡路里。但它似乎没有返回 的值,_object_因为它的值NSLog显示_(null)__xyz_。我哪里错了??

4

1 回答 1

1

整个错误是对象foodData未正确初始化。所以,初始化它

一个很好的文档 - https://developer.apple.com/library/ios/documentation/cocoa/reference/foundation/Classes/NSObject_Class/Reference/Reference.html

& 从中获取数据NSmutableDictionary

https://developer.apple.com/library/ios/documentation/cocoa/reference/foundation/Classes/NSDictionary_Class/Reference/Reference.html#//apple_ref/occ/instm/NSDictionary/objectForKey

请记住key,您在字典中用来比较的应该具有与前面定义的相同的大小写(大写 - 小写)。例如,您为键“example”存储了一个对象,但您无法使用“Example”或“EXAMPLE”检索它。您只能使用前面定义的“示例”。和


您不需要从字典中获取键数组并快速枚举它

您可以使用objectForKey:方法获取对象。祝你好运。

于 2013-11-13T04:19:28.297 回答