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

Discussion in 'iPhone/iPad Programming' started by russellelly, Dec 9, 2008.

  1. macrumors regular

    Joined:
    Jun 23, 2006
    Location:
    Glasgow, UK
    #1
    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
    Code:
    -(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView;
    and
    Code:
    - (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. macrumors regular

    Joined:
    Mar 13, 2008
    #2
    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. Moderator

    dejo

    Staff Member

    Joined:
    Sep 2, 2004
    Location:
    The Centennial State
    #3
    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