日付の配列を維持する必要はありません。n番目の行を表示する場合は、開始日にn日を追加して、それを使用できます。
したがって、開始日はインスタンス変数に格納されます。
NSDate *_startDate;
tableViewに含めるべき行数を決定するには、その年の日数を把握する必要があります(1年しか表示していないと仮定します)。
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// get the calendar
NSCalendar *calendar = [NSCalendar currentCalendar];
// get the date that points to the first day of the first month of the year containing the start date
// note that we include the era, because some calendars have more than an "AD"/"BC" kind of era
NSDateComponents *yearStartComponents = [calendar components:(NSEraCalendarUnit | NSYearCalendarUnit) fromDate:_startDate];
[yearStartComponents setMonth:1];
[yearStartComponents setDay:1];
NSDate *startOfYear = [calendar dateFromComponents:yearStartComponents];
NSDateComponents *yearDiff = [[NSDateComponents alloc] init];
[yearDiff setYear:1];
// add one year to that date
NSDate *startOfNextYear = [calendar dateByAddingComponents:yearDiff toDate:startOfYear options:0];
// figure out how many days were between the two dates
NSDateComponents *dayDiff = [calendar components:NSDayCalendarUnit fromDate:startOfYear toDate:startOfNextYear options:0];
return [dayDiff day];
}
そして、セルが必要な場合は、indexPathの「行」を開始日からの日数として使用できます。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = ...;
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *diff = [[NSDateComponents alloc] init];
[diff setDay:[indexPath row]];
NSDate *date = [calendar dateByAddingComponents:diff toDate:_startDate options:0];
NSLocale *locale = [NSLocale currentLocale];
NSString *formatted = [NSDateFormatter localizedStringFromDate:date dateStyle:NSDateFormatterShortStyle timeStyle:NSDateFormatterNoStyle locale:locale];
[[cell textLabel] setText:formatted];
return cell;
}
このアプローチにはいくつかの良い点があります。
- それは一年の長さに関係なく機能します。現在の年の日数が353日、355日、365日、366日、または384日であるかどうかに関係なく、機能します。
- 現在のカレンダーに関係なく機能します。そこにはグレゴリオ暦以上のものがあります。
NSCalendar
グレゴリオ暦、仏教暦、中国語、ヘブライ語、イスラム暦、イスラム市民、日本語、中華人民共和国、ペルシャ暦、インド暦、およびISO8601暦をサポートします。
- フォーマット文字列をハードコーディングしているわけではありません。を使用することにより
NSDateFormatterStyles
、日付に適切な省略表記を使用することになります。これは、「5/12/12」または「5 Dec '12」、あるいはまったく異なるものです。