Ios 通过循环将托管对象加载到核心数据中

Ios 通过循环将托管对象加载到核心数据中,ios,iphone,objective-c,core-data,Ios,Iphone,Objective C,Core Data,我在两个实体之间有一对多关系。我试图通过一个循环加载许多实体,但似乎没有添加任何内容。下面是一个代码示例: for(int x=0; x<[_array count]; x++) { SOCommand* newCommand = [NSEntityDescription insertNewObjectForEntityForName:@"SOCommand" inManagedObjectContext:self.managedObjectContext]

我在两个实体之间有一对多关系。我试图通过一个循环加载
许多
实体,但似乎没有添加任何内容。下面是一个代码示例:

 for(int x=0; x<[_array count]; x++)
     {
          SOCommand* newCommand = [NSEntityDescription insertNewObjectForEntityForName:@"SOCommand" inManagedObjectContext:self.managedObjectContext];
          newCommand.commandName = [(NSArray*)[_array objectAtIndex:x]objectAtIndex:0];
          newCommand.sshCommand =  [(NSArray*)[_array objectAtIndex:x]objectAtIndex:1];
          [newModule.socommand.allObjects arrayByAddingObject:newCommand];

     }
    [self.managedObjectContext save:nil];
为了检查它是否添加了内容,我尝试了以下操作:

NSArray* commands = [iteratorModule.socommand allObjects];
            if([commands count] >0){
                NSLog(@"array was populated");
            }

日志未被激发。

问题在于
arrayByAddingObject:
返回一个数组,而您没有分配给任何对象

最好的解决方案就是从newCommand对象设置关系。替换:

[newModule.socommand.allObjects arrayByAddingObject:newCommand];

还有,我认为你不理解第一行代码

[newModule.socommand.allObjects arrayByAddingObject:newCommand];
它获取与
newModule
关联的
socomand
对象的
NSSet
(类似于NSArray的集合),然后使用
allObjects
方法将其放入数组形式
arrayByAddingObject:
返回一个新数组,其中包含一个新对象,您不需要对该对象执行任何操作

newCommand.module = newModule;      //Not sure what the relationship name is here, so it might not be module   
[newModule.socommand.allObjects arrayByAddingObject:newCommand];