ioscore-datamanagedobjectcontext

Getting error after trying to save core data record


i have a view controller to add a core data record. The core data entity name is FavoriteThings, the attribute is thingname. I have a save button action called SaveButtonAction. When I tap inside the button, the text inserted in the textfield called ToDoTextField should be stored, but the app crashed showing following log error:

2013-12-09 12:30:07.488 Favorite Things[1701:a0b] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '+entityForName: nil is not a legal NSManagedObjectContext parameter searching for entity name 'FavoriteThing'' 

This is the code for the method

- (IBAction)SaveButtonAction:(id)sender {
    FavoriteThing *newEntry = [NSEntityDescription insertNewObjectForEntityForName:@"FavoriteThing" inManagedObjectContext:managedObjectContext ];
    newEntry.thingName = self.ToDoTextField.text;
    NSError *error;
    if (![self.managedObjectContext save:&error])
    {
        NSLog(@"Whoops, couldn't save:%@",[error localizedDescription]);
    }

Thank you for your time..


Solution

  • Please check the enity name and also do the following

    in YourAppDeleagte.h

    +(YourAppDeleagte*)sharedManagedContext;
    

    in YourAppDeleagte.m

      +(YourAppDeleagte*)sharedManagedContext{
    
         return (YourAppDeleagte *)[[UIApplication sharedApplication]delegate];
    }
    

    in viewController.m

    #import "YourAppDelegate.h"

    @property(nonatomic,retain)NSmanagedObjectContext *managedObjectContext;
    
    -(void)viewDidLoad{
       [super viewDidLoad];
       self.managedObjectContext=[YourAppDelagete shareManagedContext].managedObjectContext;         
     }