我很遺憾地被核心數據卡住了。我建立了1:M的關係,比方說公司和員工。顯示核心數據1:M關係的記錄
我創建公司,然後我創建Employee:
Employees *employee = (Employees *)[NSEntityDescription insertNewObjectForEntityForName:@"Employees" inManagedObjectContext:myObjectContext];
employee.name = employeeName;
employee.company = company;
NSError *error = nil;
if (![myObjectContext save:&error])
{
// Handle the error.
NSLog(@"error: %@", error.description);
}
如果我分析的SQL文件,我可以看到,對於員工記錄父列正確填入公司標識。 現在我想在我的tableview中選擇一個公司,並在另一個tableview中顯示其僱員。我實現NSFetchedResultsController
如下:
- (NSFetchedResultsController *)fetchedResultsController
{
if (fetchedResultsController != nil)
{
return fetchedResultsController;
}
//retrieve context
if (myObjectContext == nil)
{
id appDelegate = (id)[[UIApplication sharedApplication] delegate];
self.myObjectContext = [appDelegate managedObjectContext];
}
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Employees" inManagedObjectContext:myObjectContext];
[fetchRequest setEntity:entity];
[fetchRequest setFetchBatchSize:20];
NSFetchedResultsController *myFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:myObjectContext sectionNameKeyPath:nil cacheName:@"Root"];
self.fetchedResultsController = myFetchedResultsController;
fetchedResultsController.delegate = self;
return fetchedResultsController;
}
,我把它在viewDidAppear:
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
NSError *error = nil;
//call the fetch
if (![[self fetchedResultsController] performFetch:&error])
{
NSLog(@"Error with fetchedResultsController: %@, %@", error, [error userInfo]);
exit(-1);
}
[self.tableView reloadData];
}
的問題是,所有的員工,而不是隻與所選擇的公司,被顯示。
任何想法?
我將ObjectContext和Company對象傳遞給Employees視圖控制器,但我不知道如何知道哪個公司先前選擇了FetchedResultsController並僅顯示相關的Employees。有什麼建議嗎? 我發現這樣: 'NSArray * a = [company.employees allObjects]; //員工是關係' 這是正確的方式嗎?這是否意味着在Employees視圖控制器中,我不能使用Core Data NSFetchedResultsController,但是我只能在所有Employees中使用數組? – yassassin
是的,你可以這樣使用它,這是最簡單的方法,這就是我使用關係的意思。如果您發現自己需要另一個NSFetchedResults控制器,則需要使用僅爲選定公司獲取員工的NSPredicate進行設置。 –
我明白了,謝謝... 但在這一點上,1:1關係呢?例如,Employees和EmployeeDetails,一個Employee只有一個EmployeeDetail,反之亦然。 如何在EmployeeDetails視圖控制器中爲選定的員工檢索有關EmployeeDetail的信息? – yassassin