title: iphone, Saving data in to-many relationship, Core Data
body: <p>I'm working on a small iphone app using Core Data, where I got a Person and an Image entities. The relationship between Person and Image is to-many. One person to many images. </p>
  
  <p>Problem happens at save method. During saving first I need 'ADD' more than one image data, that I got from ImagePickerViewController, to Person and then 'SAVE' the Person entity to actual DB. ((in the same method))</p>
  
  <pre><code>if (managedObjectContext == nil)
  {
  managedObjectContext = [(CoreDataCombine01AppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
  }
  //???: how to init _PersonImage?
  _PersonImage = (PersonImage *)[NSEntityDescription insertNewObjectForEntityForName:@"PersonImage" inManagedObjectContext:managedObjectContext];     
  //_PersonImage = [_PersonImage init];
  //_PersonImage = [[_PersonImage alloc] init];
  _PersonImage.originalImage = imageData;
  
  managedObjectContext = nil;
  [managedObjectContext release];
  </code></pre>
  
  <p>.</p>
  
  <pre><code> if (managedObjectContext == nil)
    {
    managedObjectContext = [(CoreDataCombine01AppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
  }
  person = (Person *)[NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:managedObjectContext]; 
  [person addPersonToPersonImageObject:_PersonImage];//runTime error 
  [_PersonImage release];
  </code></pre>
  
  <p>.</p>
  
  <pre><code>NSError *error = nil;
  if (![person.managedObjectContext save:&amp;error]) {
      // Handle error
      NSLog(@"Unresolved error at save %@, %@", error, [error userInfo]);
      exit(-1);  // Fail
  }
  </code></pre>
  
  <p>then I got error saying:</p>
  
  <pre><code>"-[NSConcreteMutableData CGImage]: unrecognized selector sent to instance" 
  </code></pre>
  
  <p>and:</p>
  
  <pre><code> "*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSConcreteMutableData CGImage]: unrecognized selector sent to instance".
  </code></pre>
  
  <p>I guessed the error came from <strong>double use of NSEntityDescription from one managedObjectContext</strong>. So I just init Person class, that derived automatically from data model and manually imported, like the commented line instead of using managedObjectContext.</p>
  
  <p>It doesn't give any error but give me runtime error when I hit my save button.</p>
  
  <p>When I was using one-to-one relationship there was no problem with saving so I guess using managedObjectContext for Person is right way. However, once I use to-many relationship I need save Image data to PersonImage entity. And the entity has to be initialized in a way or another. </p>
  
  <p>What am I missing?</p>