-8

Scenario = I need to loop through an array and find how many "unread" there are and count how many to display to the user.

What I'm Looking For = something like this (this is not my real code)

for (NSDictionary *dic in self.objects) {

    [unreadCountArray addObject:dic[@"wasRead"]];

    for (YES in unreadCountArray) {

        //statements

    }
}

Question = Does anyone know how to loop through and find all of the YES booleans?

Tom Testicool
  • 563
  • 7
  • 26

2 Answers2

2

If you have an array of dictionaries, and you want to filter them, then filteredArrayUsingPredicate: is the method to use.

You can create a predicate using the key from your dictionary (predicateWithFormat:).

This will then give you an array of dictionaries that match the conditions in your predicate.

No sample code, I'm answering this on a phone.

jrturton
  • 118,105
  • 32
  • 252
  • 268
2
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"wasRead = YES"];
NSArray *arr = [array filteredArrayUsingPredicate:predicate];

Can sort a thousand objects in 0.0004 seconds.

Then just do:

for (NSDictionary *object in arr) {
    //Statements
}

Edit: actually after further experimentation, using fast-enumeration is about four times faster, about 0.0001, which if scaled to 100000 objects can be much, much faster.

NSMutableArray *test = [NSMutableArray array];

for (NSDictionary *dict in array)
    if ([dict[@"theKey"] boolValue])
        [test addObject:dict];

So for sorting, fast-enumeration is actually faster but for just a couple hundred objects, the performance increase is negligible.

And please before asking questions like this and getting downvotes, those could have been completely avoided by checking the documentation. Like this article and this article.

Milo
  • 5,041
  • 7
  • 33
  • 59