Getting number of distinct 'Days' from an NSArray of NSDate

Discussion in 'iOS Programming' started by russellelly, Dec 9, 2008.

  1. russellelly macrumors regular

    Jun 23, 2006
    Glasgow, UK
    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;
    - (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 :)
  2. drivefast macrumors regular

    Mar 13, 2008
    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.
  3. dejo Moderator


    Staff Member

    Sep 2, 2004
    The Centennial State
    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.

Share This Page