Kunal Kumar Kunal Kumar - 4 months ago 16
iOS Question

How to count the total keys in an array based on the value of that key

This might be a basic question, but I am not getting any efficient way ti do this. Suppose I have an array of multiple objects containing multiple key value like this. Now, I want the total count of

grActual
whose value is 16- Jan-13.I can iterate the array, and create a new array with key
grAcutal
and then I can count. Is there any other way to do that?

(
{
gIActual = "17-Jan-13";
grActual = "16-Jan-13";
},
{
gIActual = "18-Jan-13";
grActual = "16-Jan-13";
},
{
gIActual = "16-Jan-13";
grActual = "16-Jan-13";
},
{
gIActual = "16-Feb-13";
grActual = "16-Jan-13";
})

Answer

I believe this will do it, not that I use NSPredicate very often:

NSArray *filtered = [array filteredArrayUsingPredicate:
    [NSPredicate predicateWithFormat:@"(grActual == %@)", @"16-Jan-13"]];
NSUInteger count = [filtered count];

Tip: Store data using the correct type, which for 16-Jan-13 is NSDate, not NSString (not to mention Y2K and localization issues...).

Comments