从NSDictionary中获取单独的值

时间:2016-06-03 07:05:16

标签: ios objective-c nsdictionary

我已将数据映射到NSDictionary中。数据使用一个键和多个值进行映射。

 NSMutableDictionary *dict = [[NSMutableDictionary alloc]init]; 
     int count = 1; 
     int intval=111; 
     int intval2 = 222; 
     [dict setObject:[NSString stringWithFormat:@"%d,%d",intval,intval2]
     forKey@"%d",count];
     count++;

如何为key=1之类的密钥获取两个整数值?我需要在整数变量中单独获得值111,222。

2 个答案:

答案 0 :(得分:1)

首先,你不能将addObject(此方法用于NSMutableArray)转换为dictionay,你可以为任何键设置setObject或Setvalue。

如果您正在插入与上面相同的记录,并且只有两个整数用逗号分隔,那么您可以使用以下方式获取它:

NSString *myBothvalue = [dict valueForKey:@"count"];
NSArray *temp = [myBothvalue componentsSeparatedByString:@","];

NSInteger value1 = [[temp objectAtIndex:0] integerValue];
NSInteger value2 = [[temp objectAtIndex:1] integerValue];

希望这会对你有所帮助。

答案 1 :(得分:1)

//set object
NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
int count = 1; int intval=111; int intval2 = 222;
[dict setObject:[NSString stringWithFormat:@"%d,%d",intval,intval2] forKey:@"count"];
count++;

//Read from dictionary
NSArray *arrayofCount=[[dict valueForKey:@"count"]componentsSeparatedByString:@","];

if(arrayofCount.count>0)
{
    int readintval = [[arrayofCount objectAtIndex:0] intValue];
}
if(arrayofCount.count>1)
{
    int readintval2 = [[arrayofCount objectAtIndex:1] intValue];
}