我正在制作一个卡路里计数器,我创建了一个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_
的值。我哪里错了?
答案 0 :(得分:1)
整个错误是对象foodData
未正确初始化。所以,初始化它
&安培;从NSmutableDictionary
请记住,您在字典中用于比较的key
应该具有与之前定义的相同的大写(大小 - 小)。例如,您存储了一个键'example'的对象,但您无法使用''Example'或'EXAMPLE'来检索它。您只能使用前面定义的“示例”。和
您无需从字典和字典中获取密钥数组。快速列举
您可以使用objectForKey:
方法获取对象。祝你好运。