简体   繁体   English

iPhone核心数据:如何将NSSet从一个实体复制到另一个实体?

[英]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的实体将复制默认typesCategory 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM