我正在开发一个应用程序,它有我的iOS应用程序可以访问和终点。考虑到我正在将应用程序拼凑在一起,我已经相当远了。
无论如何,我目前被困住了,并希望得到一些帮助。从端点返回的数据看起来有点像这样:
{
"error": false,
"posts": [
{
"id": 13,
"name": "Hello World!",
"description": "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Reprehenderit, ea aliquid saepe illum deleniti. Optio, quos, eum, mollitia aperiam assumenda quidem sit quod enim consectetur doloribus animi perferendis accusamus porro.",
"user_id": 1,
"category_id": 7,
"created_at": "2014-04-15 18:49:54",
"updated_at": "2014-04-15 18:49:54",
"category": {
"id": 7,
"name": "awesome"
},
"user": {
"id": 1,
"username": "johncrossley",
"firstname": "John",
"lastname": "Crossley",
"email": "john@example.com"
}
},
{
"id": 14,
"name": "Hi There!",
"description": "Lorem ipsum dolor sit amet, consectetur adipisicing elit.",
"user_id": 1,
"category_id": 6,
"created_at": "2014-04-15 18:49:54",
"updated_at": "2014-04-15 18:49:54",
"category": {
"id": 6,
"name": "unicorns"
},
"user": {
"id": 1,
"username": "johncrossley",
"firstname": "John",
"lastname": "Crossley",
"email": "john@example.com"
}
}
]
}
无论如何我想在类别被分组到字典中的地方进行格式化,例如在“独角兽”类别下我会看到属于“独角兽”的所有帖子和真棒相同。
然后我就可以在UITableViewController中使用它来将帖子分成几个部分。
我可以轻松地在服务器端执行此操作,但不是。因为我希望数据保持按顺序。
希望这是有道理的,任何帮助都会非常感激!!
-
我已经实现了AFNetworking,所以将数据作为NSArray只是试图用它来玩。仍然有任何帮助是惊人的。
答案 0 :(得分:1)
首先在单独的数组中获取帖子:
NSArray *posts = [myData valueForKey:"posts"];
或者,如果myData是一个数组:
NSArray posts = [myData objectAtIndex:indexOfPosts];
//IndexOfPosts is an Integer containing, unsurprisingly, the index os the Posts-Subarray
声明字典和数组以保存结果:
NSMutableDictionary *results = [[NSMutableDictionary alloc] init];
NSMutableArray *unicorns = [NSMutableArray array];
NSMutableArray *awesome = [NSMutableArray array];
然后循环并排序:
for(NSDictionary *post in posts){
if([[post valueForKey:"category"] valueForKey:"name"] isEqualToString:"unicorns"]){
[unicorns addObject:post];
}else if([[post valueForKey:"category"] valueForKey:"name"] isEqualToString:"awesome"]){
[awesome addObject:post];
}
}
然后将The Arrays添加到Dictionary:
[result setObject:awesome forKey:"awesome"];
[result setObject:unicorns forKey:"unicorns"];
应该这样做。
编辑:与动态类别相同的程序:
NSMutableDictionary *result;
for(NSDictionary *post in posts){
NSString name = [[post objectForKey:"category"] objectForKey:"name"];
if([result objectForKey:name]){
[[result objectForKey:name] addObject:post];
}else{
NSMutableArray *array = [NSMutableArray arrayWithObject:post];
[result setObject:array forKey:name];
}
}