按日期对 UITableView 中的项目进行排序
因此,在我的应用程序中,我有一个 UITableView,并且在导航控制器中有一个用于添加新项目的按钮。然后,您将进入添加项目屏幕,完成后,我使用自定义委托将信息从详细信息视图控制器传递到主tableViewController
。现在我有了来自委托的信息,我将这 3 条信息放入主数组的 NSArray 中。现在我的问题是,如何按日期对详细项目进行排序。我已经尝试了 3 次(未成功),但我似乎无法弄清楚。数组和字典会变得混乱,因为它们是嵌套的。非常感谢任何帮助。
tableViewController类中的Delegate方法:
-(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];
if (!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];
}
这是我正在考虑的文件higharchy,但我似乎无法实现它。
/* file higharchy
* - theBigDict //large dictionary holding everything
* - MutableArray by day stored as objects of theBigDict
* - Array of the meals info:
* - Meal type
* - Food
*/
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以调用 NSMutableArray 上的多种方法来对其内容进行排序:
由于您有一个复杂对象数组,因此您需要编写自己的函数或比较器并调用适当的 sortUsingXxx: 方法。在将数组存储回 NSUserDefaults 之前以及在表上调用
reloadData:
之前执行此操作。这有帮助吗?
编辑:您的自定义函数或比较器必须从正在比较的两个数组元素中提取日期(传递到您的函数中)并返回适当的比较结果,例如 NSOrderedAscending 等。
There are several methods on
NSMutableArray
you can call to sort its contents: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.