2010-10-23 37 views
1

此代碼用於製作「初始數據」或「測試數據」。iPhone核心數據:如何將NSSet從一個實體複製到另一個實體?

Category實體將攜帶默認typesSubcategory實體將從Category複製默認types。 他們不會使用相同的types,因爲新的或舊的types可能會被刪除或添加到Subcategory

-(void)newCat:(NSString*)catName subCat:(NSArray*)subCatNames types:(NSArray*)typeNames{ 
//get the context 
NSManagedObjectContext *context = [self managedObjectContext]; 

//make a category 
Category *theCat = [NSEntityDescription 
     insertNewObjectForEntityForName:@"Category" 
     inManagedObjectContext:context]; 
theCat.name = catName; 

//make default types and put it in the category 
for (int i = 0; i < [typeNames count]; i++) { 
    Type *type = [NSEntityDescription 
     insertNewObjectForEntityForName:@"Type" 
     inManagedObjectContext:context]; 
    type.name = [typeNames objectAtIndex:i]; 
    [theCat addTypesObject:type]; 
} 

//make some subcategories 
//copy default types from category to subcategory 
for (int i = 0; i < [subCatNames count]; i++) { 
    Subcategory *newSubcat = [NSEntityDescription 
     insertNewObjectForEntityForName:@"Subcategory" 
     inManagedObjectContext:context]; 

    newSubcat.name = [logbookNames objectAtIndex:i]; 
    newSubcat.category = theCat; 
    [newSubcat addTypes:theCat.types]; 
} 

//save the context 
[self save]; 

} 

這種方法是我第一次打開應用程序。一旦我終止並重新打開應用程序,除了一個Subcategory實體保留types

爲什麼其他Subcategory刪除types?我擔心我只會在Category中設置一個指向默認types的指針。

如何複製Category.types並將其設置爲Subcategory.types中的類型?

設計明智,我應該創建一個新的實體來保存類別的默認類型,而不是使用默認和非默認的相同實體?

+0

嗯,我發現了一個修復程序,我不知道這是否是正確的方法,但我列舉了默認類型。 – ssj 2010-10-23 22:44:31

回答

0

你類型是一個標準的對象,你可以接受並使[類型複製] 之後,你可以做你想要的東西。

相關問題