我正在寫一個小應用程序,其中我使用coredata,我有像數據包含 數學,科學和其他書籍的數據。FetchedResultsController與部分
可以添加或刪除其他書籍,但數學和科學不能刪除,添加新學生時會默認添加。當我拿到結果時,我應該得到所有書名,包括數學和科學。
我想要做的是將數據顯示在三個部分,標題爲數學,科學和其他。數學和科學將只包含一行,即數學或科學。而其他所有書籍都應在閱讀部分。
如何着手實現這一目標?
我正在寫一個小應用程序,其中我使用coredata,我有像數據包含 數學,科學和其他書籍的數據。FetchedResultsController與部分
可以添加或刪除其他書籍,但數學和科學不能刪除,添加新學生時會默認添加。當我拿到結果時,我應該得到所有書名,包括數學和科學。
我想要做的是將數據顯示在三個部分,標題爲數學,科學和其他。數學和科學將只包含一行,即數學或科學。而其他所有書籍都應在閱讀部分。
如何着手實現這一目標?
當您創建NSFetchResultsController時,請在獲取請求中使用books表的實體名稱。
然後用這個...
NSFetchedResultsController *aController = [[NSFetchedResultsController alloc] initWithFetchRequest:request managedObjectContext:self.managedObjectContext sectionNameKeyPath:@"typePropertyName" cacheName:nil];
typePropertyName將是從一本書去的節的名稱將是路徑。
它可能只是@「的typeName」如果您直接在Book表中找到它,或者如果您與名爲type
的表有關係,那麼它可能是@「type.name」,然後該表有一個名爲name
的字段。
無論如何,這將在...
的完整代碼將是這樣的......
#pragma mark - fetched results controller
- (NSFetchedResultsController*)fetchedResultsController
{
if (_fetchedResultsController != nil) {
return _fetchedResultsController;
}
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Book"];
[request setFetchBatchSize:20];
NSSortDescriptor *sdType = [[NSSortDescriptor alloc] initWithKey:@"type.name" ascending:YES];
NSSortDescriptor *sdName = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
[request setSortDescriptors:@[sdType, sdName]];
NSFetchedResultsController *aController = [[NSFetchedResultsController alloc] initWithFetchRequest:request managedObjectContext:self.managedObjectContext sectionNameKeyPath:@"type.name" cacheName:nil];
aController.delegate = self;
self.fetchedResultsController = aController;
NSError *error = nil;
if (![self.fetchedResultsController performFetch:&error]) {
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
return _fetchedResultsController;
}
然後在tableViewController你可以有這個...
創建一個NSFetchedResultsController與區段- (NSString*)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
id <NSFetchedResultsSectionInfo> sectionInfo = [self.fetchedResultsController sections][section];
return [sectionInfo name]
}
然後這將使用部分名稱作爲每個部分的標題。
感謝您的回覆,但在我的實體中沒有用於分區的屬性。該類別就像數組中一樣,如果主題名稱是數學,它應該把它放在數學部分,如果主題名稱是科學,那麼它應該去科學部分,否則它應該落在其他部分。 – Ayan
然後只需使用字段名稱:D – Fogmeister
這是sectionname keypath進場的地方。如果你有一些叫科目的屬性,它們包含科學,數學和其他屬性,那麼在fetchedresultscontroller performFetch:方法中使用sectionNameKeyPath:作爲主題,所有其他將與蘋果模板提供的相同。 – Sandeep