开发者

Sort items in a UITableView by date

So in my app, I have a UITableView, and in the navigation controller there is a button to add a new item. This than takes you to an add an item screen and when you finish, i use a custom delegate to pass the information from the detail viewController to the main tableViewController. Now that I have the info from delegate, I take the 3 pieces of info and put them in an NSArray in my main Array. Now my question is, how can I sort the detail items by date. I have tried (unsuccessfully) 3 times now and I can't seem to figure it out. The arrays and dictionarys get confusing because they are nested. Any help is greatly appreciated.

The Delegate Method in the tableViewController class:

-(void)finishedAddingFoodItemFromDetail:(NSDate *)date whatWasEaten:(NSString *)whatFood whichMeal:(NSString *)meal{

NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MMMM d, yyyy"];
NSString *dateString = [[NSMutableString alloc] init];
dateString = [dateFormatter stringFromDate:date];

i开发者_运维问答f (!self.theArray) {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    if ([defaults objectForKey:@"theArray"]) {
        self.theArray = [defaults objectForKey:@"theArray"];
    }
    else{
        self.theArray = [[NSMutableArray alloc] init];
    }
}
[self.theArray addObject:[NSArray arrayWithObjects:dateString, meal, whatFood, nil]];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:self.theArray forKey:@"theArray"];

[self.tableView reloadData];
[self dismissModalViewControllerAnimated:YES];
}

This is the file higharchy I was thinking of, but I can't seem to implement it.

/*  file higharchy
 *   - theBigDict     //large dictionary holding everything
 *       - MutableArray by day stored as objects of theBigDict
 *       - Array of the meals info:
 *           - Meal type
 *           - Food
 */


There are several methods on NSMutableArray you can call to sort its contents:

– sortUsingDescriptors:
– sortUsingComparator:
– sortWithOptions:usingComparator:
– sortUsingFunction:context:
– sortUsingSelector:

Since you have an array of complex objects, you will need to write your own function or comparator and call the appropriate sortUsingXxx: method. Do this before you store the array back into NSUserDefaults and before calling reloadData: on your table.

Does this help?

EDIT: Your custom function or comparator will have to pull out the date from the two array elements being compared (passed into your function) and return the appropriate comparison results, e.g. NSOrderedAscending, etc.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜