Pregunta

I am making a calorie counter and I have created an UIAlertView which gives me list of food items. I have made a NSMutableDictionary containing the food and the calories:

@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

In another class, I have created an UIAlertView which gives a list of food items. This is the code snippet for the item 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];

}

I calculate the total calories by using the value entered by the user in the _RiceText_ and the value of the _object_ returned for a specific key (in this case rice). But it seems not to be returning the value of the _object_ as the NSLog shows _(null)_ for the value of _xyz_. Where am I going wrong??

¿Fue útil?

Solución

The whole error is that the object foodData isn't initialized properly. So, initialize it

A nice documentation - https://developer.apple.com/library/ios/documentation/cocoa/reference/foundation/Classes/NSObject_Class/Reference/Reference.html

& fetching data from NSmutableDictionary

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

Remember the key that you use to compare in dictionary should have same casing (capital - small) as defined earlier. e.g You store an object for key 'example' but you can not retrieve it using ''Example' or 'EXAMPLE'. You can only use 'example' as defined earlier. And


You don't need to get arrays of keys from dictionary & fast-enumerate it

You can just get the object using objectForKey: method. Good luck.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top