要麼我不理解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);
當我執行此操作時,我在控制檯中得到重複的名稱。爲什麼?
還有那個dang mutableCopy了。人們在哪裏得到這些? – TechZen 2010-07-15 00:18:32
就mutableCopy而言,這是需要的,因爲我使用NSMutableArray作爲提取結果。我想我並不需要它可以改變,但... – 2010-07-15 19:42:55