0
votes

I have a simple app with AppDelegate and MainController - I have passed the managedObjectContext to the MainController (I think successfully) but I receive an error when added an object to the context.

Code:

 @implementation AppDelegate

 -(void)applicationDidFinishLaunching:(NSNotification *) aNotification
 {
  // this line is wrong:  MainController *controller = [[MainController alloc] init];
  controller.managedObjectContext = self.managedObjectContext;
 }


  @interface MainController : NSObject

  @property (nonatomic, strong) NSManagedObjectContext *managedObjectContext;


  @implementation MainController

  -(IBAction)addItem:(id)sender {

  NSManagedObject *newObject = [NSEntityDescription
                               insertNewObjectForEntityForName:@"Person"
                               inManagedObjectContext: self.managedObjectContext];

   //The above line gives an error

ERROR: +entityForName: nil is not a legal NSManagedObjectContext parameter search for entity name "Person"

If I change the code and do everything in the AppDelegate, everything works without issues.

I am not sure what is going on.

[EDIT] I needed to create an IBOutlet from the MainController object in IB to the AppDelegate - thanks Nofel.

1
did you @synthesized managedObjectContext in MainController ? and Why don't you make a MainController property in your AppDelegate ? - Nofel Mahmood
Yes, first I had it without the synthesize, then added it - no change. - littleDrummerBoy
ok ... Consider also doing controller.managedObjectContext=[self managedObjectContext]; instead of controller.managedObjectContext = self.managedObjectContext; - Nofel Mahmood
No change - same error. - littleDrummerBoy

1 Answers

0
votes

I think it should be like this:

Person *person = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:_managedObjectContext];
[person setName:someNameTextField]; // if you want to set some properties
[_managedObjectContext save:nil]

It depends on how you create your Core-Data model and what you use in you appDelegate. Best way is to watch some tutorial or Developer Library first.