如何在UIAlertView中使用NSMutableDictionary?

时间:2013-11-05 23:25:17

标签: ios6 uialertview nsmutabledictionary

我正在制作一个卡路里计数器,我创建了一个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_的值。我哪里错了?

1 个答案:

答案 0 :(得分: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:方法获取对象。祝你好运。