2010-07-14 55 views
0

要麼我不理解Core Data中術語「uniquing」的含義,要麼我沒有正確讀取數據。我有一個非常簡單的數據模型。三個實體:社區,資產和類別。每個社區都與多個類別有關係。每個類別都與多個資產有關係。每個創建的資產必須只有一個類別。iPhone SDK:核心數據和uniquing?

在我發佈的代碼中,我想輸出特定社區所有類別的控件。我認爲,由於Core Data的獨特功能,每次只能存在一個同名的類別(名稱是類別的唯一屬性)。但是,當我打印到控制檯時,我收到重複的類別名稱。

// Fetch Community instances in the database, and add them to an NSMutableArray 
NSFetchRequest *request = [[NSFetchRequest alloc] init]; 
NSEntityDescription *community = [NSEntityDescription entityForName:@"Community" inManagedObjectContext:managedObjectContext]; 
[request setEntity:community]; 

// Only return the community instances that have the cityName of the cell tapped in the CommunitiesNonEditableTableViewController 
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(cityName like %@)", cellCityName]; 
[request setPredicate:predicate];  

NSError *error; 
NSMutableArray *mutableFetchResults = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy]; 

if (mutableFetchResults == nil) { 
    // Handle the error. 
} 

// Set communitiesArray with mutableFetchResults 
[self setCommunitiesArray:mutableFetchResults]; 

[mutableFetchResults release]; 
[request release]; 

// Creates a community instance using the community stored in the array at index 0. This is the only community in the array. 
Community *communityInstance; 
communityInstance = [communitiesArray objectAtIndex:0]; 

// Retrieves existing categories of assets in the community, and adds them to an NSSet 
NSSet *communityCategoriesSet = communityInstance.categories; 

// Converts NSSet to an NSArray with each category as an index 
NSArray *communityCategoriesArray = [communityCategoriesSet allObjects]; 

// For loop that iterates through the array full of categories, retrieves the names of each category, and adds it to an NSMutableArray 
categoryNames = [[NSMutableArray alloc] init]; 
int i; 
for (i = 0; i < [communityCategoriesArray count]; i++) { 
    Category *categoryInstance; 
    categoryInstance = [communityCategoriesArray objectAtIndex:i]; 
    [categoryNames addObject:categoryInstance.name]; 
} 

// Prints array full of category names to console 
NSLog(@"%@", categoryNames); 

當我執行此操作時,我在控制檯中得到重複的名稱。爲什麼?

+0

還有那個dang mutableCopy了。人們在哪裏得到這些? – TechZen 2010-07-15 00:18:32

+0

就mutableCopy而言,這是需要的,因爲我使用NSMutableArray作爲提取結果。我想我並不需要它可以改變,但... – 2010-07-15 19:42:55

回答

1

抽樣意味着對象圖中的每個對象都是唯一的。這並不意味着任何兩個對象的屬性都不相同。非抽象是關於關係而不是屬性。沒有兩個對象可以在對象圖中佔據完全相同的位置。

至於爲什麼你在輸出中得到多個類別:最簡單的解釋是communityInstance.categories是一對多的關係。 (因爲它有一個複數名稱並將其分配給集合。)在一對多關係中,上下文不強制關係另一端的單個對象。

+0

謝謝。我以完全不同的方式進行了探討。 – 2010-07-15 22:52:02