设想:
我有一个费用跟踪 iOS 应用程序,我将费用详细信息视图控制器中的费用存储到表视图(带有获取的结果控制器)中,该表视图显示费用列表以及类别、金额和日期。我的实体“金钱”中确实有一个日期属性,它是支出或收入的父实体。
问题:
我想要的是基本上按月对我的费用进行分类,并将其显示为部分标题标题,例如:(2012 年 11 月 1 日 - 11 月 30 日),它根据该特定月份显示费用金额和相关内容。该视图中提供了两个按钮,如果我按右侧按钮,它会将月份增加一个月(2012 年 12 月 1 日 - 12 月 31 日),类似地,左侧按钮会将月份减少一个月。
我将如何实现这一目标?我正在尝试下面的代码 - 这有点工作。假设我当前的节标题为(Nov1 - Nov 30, 2012),当我按左按钮时,它给我节标题(Oct 1 - Oct 30, 2012),这是错误的,它应该是 Oct 31, 2012而不是 2012 年 10 月 30 日。
- (NSDate *)firstDateOfTheMonth
{
self.startDate = [NSDate date];
NSCalendar* calendar = [NSCalendar currentCalendar];
[calendar setTimeZone:[NSTimeZone localTimeZone]];
NSDateComponents* components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:self.startDate];
[components setDay:1];
firstDateOfTheMonth = [[calendar dateFromComponents:components] retain];
return firstDateOfTheMonth;
}
- (NSDate *)lastDateOfTheMonth
{
NSCalendar* calendar = [NSCalendar currentCalendar];
[calendar setTimeZone:[NSTimeZone localTimeZone]];
NSDateComponents* components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:firstDateOfTheMonth];
[components setMonth:[components month]+1];
[components setDay:0];
lastDateOfTheMonth = [[calendar dateFromComponents:components] retain];
return lastDateOfTheMonth;
}
然后我有一个名为“monthCalculation”的方法,在其中调用上述两个方法。
- (void)monthCalculation
{
[self firstDateOfTheMonth];
[self lastDateOfTheMonth];
}
现在,当我按下左侧按钮时,以下代码(将月份减少一个月):
- (IBAction)showPreviousDates:(id)sender
{
[self monthCalculation];
NSDateComponents *dateComponents = [[[NSDateComponents alloc] init] autorelease];
[dateComponents setMonth:-1];
NSDate *newDate1 = [[NSCalendar currentCalendar]
dateByAddingComponents:dateComponents
toDate:firstDateOfTheMonth options:0];
NSDate *newDate2 = [[NSCalendar currentCalendar]
dateByAddingComponents:dateComponents
toDate:lastDateOfTheMonth options:0];
self.startDate = newDate1;
self.endDate = newDate2;
NSLog(@" self start date in previous mode =%@", self.startDate);
NSLog(@" self end date in previous mode =%@", self.endDate);
}
当我按下右键时,以下代码(将月份增加一个月):
- (IBAction)showNextDates:(id)sender
{
[self monthCalculation];
NSDateComponents *dateComponents = [[[NSDateComponents alloc] init] autorelease];
[dateComponents setMonth:1];
NSDate *newDate1 = [[NSCalendar currentCalendar]
dateByAddingComponents:dateComponents
toDate:firstDateOfTheMonth options:0];
NSDate *newDate2 = [[NSCalendar currentCalendar]
dateByAddingComponents:dateComponents
toDate:lastDateOfTheMonth options:0];
self.startDate = newDate1;
self.endDate = newDate2;
NSLog(@" self start date in previous mode =%@", self.startDate);
NSLog(@" self end date in previous mode =%@", self.endDate);
}
我做得对吗?或者有更好的方法来实现这一目标?任何帮助将不胜感激。