imbeginner_sorry imbeginner_sorry - 3 months ago 28
iOS Question

how to Filter the Json data in ios objective c

I have a problem with JSON parsing.

I get the JSON data and I want to display the items that matched by restid.

I have a tableView to display different restaurant information and every restaurant also have their own comment cell to comment this restaurant.

So,I would filter the JSON data.

Let each restaurant comment cell can get own comment.


This is my JSON:

(
{
comment = "very good";
food = chicken;
name = Tom;
restid = 1;
score = 4;
},
{
comment = nice;
food = coffee;
name = Jack;
restid = 3;
score = 3;
},
{
comment = tasty;
food = pizza;
name = Mary;
restid = 17;
score = 5;
},
{
comment = unlike;
food = none;
name = Gigi;
restid = 33;
score = 1;
},
{
comment = delicious;
food = juice;
name = Bruce;
restid = 45;
score = 5;
}
)


This is my code:



It can display all data in my tableView and all the same data in different restaurant comment cell.

- (void)getCommentInfo:(id)sender {

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{


NSURL *url = [NSURL URLWithString:@"http://localhost:8888/foodComment_json.php"];

NSData *data = [NSData dataWithContentsOfURL:url];
NSArray *comment = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(@"Comment is %@",comment);

self.commentArray = [NSMutableArray arrayWithArray:comment];

dispatch_async(dispatch_get_main_queue(), ^{
[self.detailCommentTableView reloadData];
});
});

}


Thanks!

Answer

Try this, I didn't test the code so let me know if you have problems.

NSArray *filteredArray = [comment filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(id elem, NSDictionary *bindings) {
    return ([elem objectForKey:@"restid"] == <your_rest_id>)
}]];
Comments