PDA

View Full Version : Getting number of distinct 'Days' from an NSArray of NSDate




russellelly
Dec 9, 2008, 05:40 AM
I'm working on an app which uses a UITableView to display content over a time period. The idea is that each section should be a day, and each day can have a varying number of objects, each of which appear as a list item. Easy enough.

The objects are stored in one NSArray, which contains an NSDate, the Text which should be displayed in the list and some other stuff.

I'm trying to implement the -(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView; and - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section; methods, but am somewhat stuck.

The first method has to work out how many distinct days there are in the NSArray, I think, but there's no obvious method to do this. I can use an NSDateFormatter to just get the date and ignore the time, but then it's a problem finding how many distinct strings there are (since containsObject() won't have the same object for the two 'different NSStrings with the same text (I think?).

Anyway, before I plough head first into this and redo my datastructure or implement some highly inefficient algorithm, I was wondering if anyone here has tackled something similar and perhaps has some inspiration :)



drivefast
Dec 9, 2008, 12:49 PM
to determine its calendaristic day, take each date in your dataset, convert it to an epoch, and divide it by 60*60*24, which is the number of seconds in a day. (i'm talking about integer division.) keep track of how many such distinct results you get. this is up to you how to do it. one simple idea is to have an array of unsigned integers. each time you calculate such division, you would add the result to the array, but only if it doesnt exist in there already. the number of distinct values is the count property of the array.

dejo
Dec 9, 2008, 12:52 PM
I would suggest creating a property to store the number of sections, have a method to determine the number of sections that updates that property whenever the table data is (re)loaded, and then just have the numberOfSectionsInTableView method use the value from that property.