我想將我的tableview分成每個月的部分。我開始使用DateSectionTitles蘋果的例子。首先,我在覈心數據庫中添加了一個屬性'sectionIdentifier'。然後在我的managedobject子類中添加了這個方法。使用fetchedresultcontroller爲每個月設置一個不同的部分
- (NSString *)sectionIdentifier {
// Create and cache the section identifier on demand.
[self willAccessValueForKey:@"sectionIdentifier"];
NSString *tmp = [self primitiveSectionIdentifier];
[self didAccessValueForKey:@"sectionIdentifier"];
if (!tmp) {
/*
Sections are organized by month and year. Create the section identifier as a string representing the number (year * 1000) + month; this way they will be correctly ordered chronologically regardless of the actual name of the month.
*/
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit) fromDate:[self date]];
tmp = [NSString stringWithFormat:@"%d", ([components year] * 1000) + [components month]];
[self setPrimitiveSectionIdentifier:tmp];
}
NSLog(@"tmp: %@",tmp);
return tmp;
}
這是我在titleForHeaderSection
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
id <NSFetchedResultsSectionInfo> theSection = [[self.fetchedResultsController sections] objectAtIndex:section];
/*
Section information derives from an event's sectionIdentifier, which is a string representing the number (year * 1000) + month.
To display the section title, convert the year and month components to a string representation.
*/
static NSArray *monthSymbols = nil;
if (!monthSymbols) {
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setCalendar:[NSCalendar currentCalendar]];
monthSymbols = [formatter monthSymbols];
}
NSInteger numericSection = [[theSection name] integerValue];
NSInteger year = numericSection/1000;
NSInteger month = numericSection - (year * 1000);
NSString *titleString = [NSString stringWithFormat:@"%@ %d", [monthSymbols objectAtIndex:month-1], year];
NSLog(@"titelstring is: %@",titleString);
return titleString;
}
做我的電話號碼rowsInSection我做到這一點。
id <NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections] objectAtIndex:section];
NSInteger count = [sectionInfo numberOfObjects];
return count;
這對我NumberOfSectionsInTableview
NSInteger count = [[self.fetchedResultsController sections] count];
return count;
任何人可以幫助?
在此先感謝!
到底哪裏出問題了
首先關閉所有它不打印我的日誌中的NSLog(@ 「TMP:%@」,TMP); 同時,我得到以下錯誤:
CoreData: error: (NSFetchedResultsController) A section returned nil value for section name key path 'sectionIdentifier'. Objects will be placed in unnamed section
2012-10-10 10:41:17.475 RacingGenk[15785:c07] *** Terminating app due to uncaught exception 'NSRangeException', reason: '-[__NSCFArray objectAtIndex:]: index (-1 (or possibly larger)) beyond bounds (12)'
NSPostWhenidle,你編輯了什麼? – Steaphann
您是否在創建抓取的結果控制器時設置了'sectionNameKeyPath:@「sectionIdentifier」'? - (這個問題很古老,但是因爲某種原因關閉了並重新打開,以致它再次顯示爲「主動」。也許問題已經解決了嗎?) –