0

Using Json I have retrieve some values to UITableViewCell

NSString *sample = [[array objectAtIndex:indexPath.row] objectForKey:@"food"];

I am getting 1,2,3,4,6 in my sample string values

But I want to show like, if for example 1=apple 2=grape 3=orange 4=pineapple 5=lemon 6=All

I want the result to be apple,grape,orange,pineapple,All in my sample string values

RKRK
  • 1,284
  • 5
  • 14
  • 18

3 Answers3

1

In Objective-C there is no built in enums available for String types. You can declare enums as Integer and then make a function or an array of strings which return the string value for that enum.

Declare in your .h file.

typedef NS_ENUM(NSInteger, FRUIT) {
    APPLE = 1,
    GRAPE,
    ORANGE,
    PINEAPPLE,
    LEMON,
    All
};

extern NSString * const FRUITString[];

Define in your .m file.

NSString * const FRUITString[] = {
    [APPLE] = @"APPLE",
    [GRAPE] = @"GRAPE",
    [ORANGE] = @"ORANGE",
    [PINEAPPLE] = @"PINEAPPLE",
    [LEMON] = @"LEMON",
    [All] = @"All"
};

and you can use it like:

NSLog(@"%@", FRUITString[APPLE]);
// OR
NSLog(@"%@", FRUITString[1]);

Output: APPLE

Based on your comment: if food values is "food":"1,2" I want to show "apple,grape"

NSString *foodValue = @"1,2";
NSArray *values = [foodValue componentsSeparatedByString:@","];
NSMutableArray *stringValues = [[NSMutableArray alloc] init];
for (NSString *value in values) {
    [stringValues addObject:FRUITString[[value integerValue]]];
}
NSLog(@"%@", [stringValues componentsJoinedByString:@","]);

APPLE,GRAPE

TheTiger
  • 13,264
  • 3
  • 57
  • 82
0

Define a NSDictionary with your required mapping, and fetch the value from your mapping dictionary:

NSDictionary *foodDict = @{
  @"1": @"apple",
  @"2": @"grape",
  @"3": @"orange",
  @"4": @"pineapple",
  @"5": @"lemon",
  @"6": @"all"
};

NSString *sample = [[array objectAtIndex:indexPath.row] objectForKey:@"food"];

NSString *sampleValue= [foodDict valueForKey:sample];

"sampleValue" is your required String Value needed. (Cast it to NSString if required)

partha_devArch
  • 414
  • 2
  • 10
0

Change your code objectForKey@"" to valueForKey@""

NSString *sample = [[array objectAtIndex:indexPath.row] valueForKey:@"food"];
Vinu Jacob
  • 393
  • 2
  • 15
  • This is the wrong way to fetch the key. We should not use `valueForKey:`. `objectForKey:` is right way. – TheTiger Jul 23 '19 at 07:52
  • If we want to get the value inside the key "food" we need to use valueForKey: – Vinu Jacob Jul 23 '19 at 07:54
  • You really need to read [this](https://stackoverflow.com/questions/1062183/difference-between-objectforkey-and-valueforkey) then. Don't miss this. – TheTiger Jul 23 '19 at 07:56