views:

43

answers:

3

Hi folks,

The subject is vague because I'm not sure how to articulate in one sentence what I want.

Here goes:

I have an NSArray of NSDictionaries. Each NSDictionary represents one day of the calendar year. Each NSDictionary has a key "date" with a value of NSDate. There should be 365 NSDictionary items in the array. The dictionary is created by a server that I don't control, and it sometimes is missing as many as 100 days.

I need to ensure the array has 365 dictionaries, each one day later than the next.

I currently sort the array by date, iterate through it, copying the NSDictionaries from the current array to a new array. While so doing, I compare the current Dictionary's date value with the date value for the next dictionary. If there is more than one day between the two dates, I add enough new dictionaries to the new array to cover those missing days (and set their dates accordingly), then continue through.

Since the dates are supposed to ordered, I wonder if there is not already a mechanism in the framework or language that I can use to say "Here is an array, and this keypath is supposed to be consecutive. Find and create the elements that are missing, and here's a block or method you can use to initialize them".

Something about my method just feels poorly implemented, so I turn to you. Thoughts?

Thanks.

+1  A: 

The way you did it sounds perfectly sane, and there is nothing to my knowledge that will do it automatically in the base framework.

Joshua Weinberg
A: 

This code will sort them.

NSArray *dates;  // wherever you get this...
NSArray *sortedDates = [dates sortedArrayUsingComparator:^(id obj1, id obj2) 
    {
    return [[obj1 valueForKey:@"date"] compare:[obj2 valueForKey:@"date"]];
    }];

As for creating the missing entries, you'll have to do that yourself.

NSResponder
Thanks for the sample code for the comparison.
Woodster
A: 

You don't need to do the sort:

  1. Create an array with 365 (or 366) placeholder dictionaries (you can possibly use the same one for all slots, or use NSNull)
  2. iterate through the passed in array and figure out which day each of the dictionaries is for. Place each dictionary in its rightful slot in your array.
JeremyP
THanks. That's a technique to consider for sure.
Woodster