[英]iPhone Core Data: How to copy NSSet from one entity to another?
This code is used to make "initial data" or "test data". 此代码用于制作“初始数据”或“测试数据”。
The Category
entity will carry default types
. Category
实体将带有默认types
。 The Subcategory
entity will copy default types
from the Category
. 该
Subcategory
的实体将复制默认types
从Category
。 They wouldn't be using the same types
because new or old types
may be deleted or added to the Subcategory
. 他们不会使用相同的
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];
}
This method works the first time I open the app. 第一次打开应用程序时此方法有效。 Once I terminate and reopen the app, all but one
Subcategory
entity retains the types
. 一旦我终止并重新打开该应用程序,除一个
Subcategory
实体之外的所有实体都保留types
。
Why is the other Subcategory
removing their types
? 为什么其他
Subcategory
删除其types
? I fear that I'm only setting a pointer to the default types
in the Category
. 我担心只设置一个指向
Category
默认types
的指针。
How do I make a copy Category.types
and set it as the types in Subcategory.types
? 如何复制
Category.types
并将其设置为Subcategory.types
的类型?
Design wise, should I create a new entity to hold default types for the Category instead of using the same entity for defaults and non-defaults? 在设计方面,我是否应该创建一个新实体来保存类别的默认类型,而不是使用相同的实体作为默认值和非默认值?
您键入的内容是一个标准对象,您可以接收并进行[types copy](类型复制),然后您可以使用它进行所需的操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.