这是我的数据。
NSDictionary *dictResponse = [[NSDictionary alloc]init];
//Here is dictResponse value is
( {
"created_on" = "0000-00-00 00:00:00";
id = 627;
"modified_on" = "0000-00-00 00:00:00";
name = "";
"user_id" = 99;
},
{
"created_on" = "2016-05-06 14:43:45";
id = 625;
"modified_on" = "2016-05-06 14:43:45";
name = Ggg;
"user_id" = 99;
},
{
"created_on" = "2016-05-03 17:21:52";
id = 623;
"modified_on" = "2016-05-03 17:21:52";
name = Qwerty;
"user_id" = 99;
},
{
"created_on" = "2016-04-29 20:12:38";
id = 601;
"modified_on" = "2016-04-29 20:12:38";
name = Teat2;
"user_id" = 99;
},
{
"created_on" = "2016-04-29 20:12:27";
id = 600;
"modified_on" = "2016-04-29 20:12:27";
name = Test1;
"user_id" = 99;
},
{
"created_on" = "2016-05-09 13:04:00";
id = 626;
"modified_on" = "2016-05-09 13:04:00";
name = Testios;
"user_id" = 99;
})
现在我想访问完整的一组对象,即
{
"created_on" = "2016-04-29 20:12:27";
id = 600;
"modified_on" = "2016-04-29 20:12:27";
name = Test1;
"user_id" = 99;
}
来自我的 dictResponse
所以我用的时候 dictResponse [0]或dictResponse 1 ..我收到错误,那么如何从NSDictionary中检索整个一组?
答案 0 :(得分:0)
您无法使用索引(如dictResponse [0])访问字典中的对象。字典中的对象没有索引,它们有密钥。要从字典中获取对象,请使用objectForKey方法:
NSObject* myObject = [dictResponse objectForKey:@"my_key"];
答案 1 :(得分:0)
你可以这样做:
id arrResponse = dictResponse;
if ([arrResponse isKindOfClass:[NSArray class]] && arrResponse != nil && arrResponse != (id)[NSNull null])
{
NSArray *arrResults = arrResponse;
//if you want retrieve specific entries then here is the code for that
for (int i = 0 ; i<arrResults.count; i++) {
NSString *strName = [[arrResults objectAtIndex:i]valueForKey:@"name"];
NSString *strCreated_on = [[arrResults objectAtIndex:i]valueForKey:@"created_on"];
NSString *strModified_on = [[arrResults objectAtIndex:i]valueForKey:@"modified_on"];
NSInteger userID = [[arrResults objectAtIndex:i]valueForKey:@"user_id"];
}
}
答案 2 :(得分:0)
您的问题没有给出足够详细信息,因此以下是猜测:
所以当我使用
dictResponse[0]
或dictResponse[1]
时,我会收到错误
你永远不会说你得到了什么错误。我猜你得到编译错误而不是执行错误?
您似乎知道您的代码错误,如您所写的评论:
是的我知道这不是有效的字典值,但是可以在NSDictionary中得到类似值的东西,所以问题没有错,是的,我的回答是字典数组。来自控制台日志的方法我可以给dictResponse [0]并按预期打印第一部分。
确切地说,你可以打破类型系统并将数组引用存储到一个变量中,该变量被键入为包含字典引用,但这样做不是一个好主意!
当编译器看到dictResponse[0]
时,它在语法上将其识别为数组索引操作,因此它在dictResponse
上查找进行数组索引的方法。所有它都知道dictResponse
,并记住这是在编译时发生的 ,是你说它是NSDictionary *
,所以它寻找支持的数组索引方法NSDictionary
并且找不到一个,给出错误:
读取在'NSDictionary *'
类型的对象上找不到的数组元素的预期方法
尝试正确输入变量并查看代码是否有效。
HTH