2013-01-31 128 views
1

我有一個包含三個實體的核心數據模型:Notification,GroupCustomer。這些是它們之間的關係:對於核心數據中的多對多關係,sectionNameKeyPath的值

  • 一位顧客屬於很多羣體,一個羣體可以有很多顧客。
  • 通知被髮送(屬於)到一個組,並且一個組可以接收(有)很多通知。

我想顯示所有通知按客戶分組的UITableView。我創建了一個NSFetchedResultsController這樣的:

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; 
fetchRequest.fetchBatchSize = 10; 
fetchRequest.predicate = nil; 

NSEntityDescription *entity = [NSEntityDescription entityForName:@"Notification" 
              inManagedObjectContext:self.managedObjectContext]; 
fetchRequest.entity = entity; 

// Default sort descriptors are built in a separate custom method 
NSArray *sortDescriptors = [self getDefaultSortDescriptorsForEntity:entity]; 
fetchRequest.sortDescriptors = sortDescriptors; 

return [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest 
              managedObjectContext:self.managedObjectContext 
        sectionNameKeyPath:@"group.customers.firstName" 
          cacheName:nil]; 

假設這是檢索按客戶分組的所有通知的有效途徑(我不知道,要麼)的iOS拋出以下異常:

@"Failed to fetch all Notification objects" 
@"Reason: Invalid to many relationship in setPropertiesToFetch: (group.customers.firstName) (NSInvalidArgumentException)" 

我已經審查了一次又一次的關係,看看是否有遺漏,一切似乎都是正確的。我可以爲所有實體創建和刪除對象,並且它們之間的鏈接也是正確的。

我的問題是:是否有可能遍歷sectionNameKeyPath值中的幾個關係?在這種情況下應該如何處理多對多的關係?

+0

「通知」可以屬於多個「客戶」。您是否想要在其所屬的每個「客戶」部分中顯示通知? –

+0

@MartinR是的,在這個特定的應用程序中,可以在幾個部分重複相同的通知。 – elitalon

+1

我不認爲這是可能的與獲取結果控制器,因爲FRC無法返回具有重複元素的對象列表。 –

回答

2

是的,你可以做到這一點。只需使用FRC獲取客戶並將sectionNameKeyPath設置爲nil即可。

部分
返回的結果數是您的部分數。用客戶數據填充節標題。


第行的數目將是customer.notifications.count。爲了填充行,確保notifications以某種方式進行排序(比如,按日期),並與像這樣相應地顯示它們:

NSArray *orderedNotifications = 
    [customerForSection.notifications sortedArrayUsingDescriptors: 
    @[[NSSortDescriptor sortDescriptorWithKey:@"date" ascending:NO]]]; 
Notification *notificationToBeDisplayed = 
    [orderedNotifications objectAtIndex:indexPath.row]; 

一個選擇 - 推薦 - 解決辦法是改變數據模型。您可以直接將通知與所有客戶相關聯。這將帶來額外的好處,即使組成員身份發生變化,通知仍然與正確的客戶相關聯。

+0

客戶沒有直接與通知關聯,但有很多組,所以我不能執行'customer.notifications.count' – elitalon

+0

FRC在這裏有用嗎?FRC將跟蹤對「客戶」對象的更改,但不會跟蹤關聯的「通知」對象。 –

+0

@elitalon然後它應該是'customer.groups.notifications.count'。相同的概念。但請參閱我的編輯和其他解決方案。 – Mundi