I have created a simple 1 entity data model through Core Data. I add an entity in "didFinishLaunchingWithOptions" of "AppDelegate". Then, I am trying to load the data of the model to an array and then a table view.
I am aware that there are similar post, but I still can't find out whats wrong with my code.
List of things I have tried and checked:
The entity is added properly into the model
I have already checked the entity names and they are correct.
I have tried deleting the app and clean rebuilding it but still nothing.
So there must be a more major issue with my code. Any help is appreciated.
Here is my error:
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '+entityForName: could not locate an NSManagedObjectModel for entity name 'FavoritesInfo'
AppDelegate.h
#import <UIKit/UIKit.h>
#import "favTable.h"
#interface AppDelegate : UIResponder <UIApplicationDelegate>
#property (strong, nonatomic) UIWindow *window;
#property (strong, nonatomic) favTable *viewController;
#property (strong, nonatomic) UINavigationController *navController;
#property (nonatomic, retain, readonly) NSManagedObjectModel *managedObjectModel;
#property (nonatomic, retain, readonly) NSManagedObjectContext *managedObjectContext;
#property (nonatomic, retain, readonly) NSPersistentStoreCoordinator *persistentStoreCoordinator;
- (NSURL *)applicationDocumentsDirectory; // reference files for core data
#end
AppDelegate.m
#import "AppDelegate.h"
#implementation AppDelegate
#synthesize window = _window;
#synthesize viewController = _viewController;
#synthesize navController = _navController;
#synthesize managedObjectContext = _managedObjectContext;
#synthesize managedObjectModel = _managedObjectModel;
#synthesize persistentStoreCoordinator = _persistentStoreCoordinator;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
NSManagedObjectContext *context = [self managedObjectContext];
NSManagedObject *favoritesInfo = [NSEntityDescription
insertNewObjectForEntityForName:#"FavoritesInfo"
inManagedObjectContext:context];
[favoritesInfo setValue:#"Product 1" forKey:#"name"];
[favoritesInfo setValue:[NSNumber numberWithInt:15] forKey:#"score"];
NSError *error;
if (![context save:&error]) {
NSLog(#"Whoops, couldn't save: %#", [error localizedDescription]);
}
return YES;
}
Then in the class of the table viewcontroller favtable.h
#import <UIKit/UIKit.h>
#interface favTable : UITableViewController <NSFetchedResultsControllerDelegate>
{
NSFetchedResultsController *fetchedResultsController;
NSManagedObjectContext *managedObjectContext;
NSArray *favArr;
int num;
}
#property (nonatomic, strong) NSArray *favArr;
#property (nonatomic, retain) NSManagedObjectContext *managedObjectContext;
#property (nonatomic, retain) NSFetchedResultsController *fetchedResultsController;
#end
favtable.m viewdidload
#import "favTable.h"
#import "AppDelegate.h"
#interface favTable ()
#end
#implementation favTable
#synthesize favArr;
#synthesize spVC;
#synthesize managedObjectContext = _managedObjectContext;
#synthesize fetchedResultsController;
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.title = #"Favorites";
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription
entityForName:#"FavoritesInfo" inManagedObjectContext:managedObjectContext];
[fetchRequest setEntity:entity];
NSError *error=nil;
self.favArr=[managedObjectContext executeFetchRequest:fetchRequest error:&error];
if (error!=nil) {
NSLog(#" fetchError=%#,details=%#",error,error.userInfo);
}
}
Your managedObjectContext is not set in your ViewController.
Set it in your AppDelegate didFinishLaunchingWithOptions, usually looks like:
ViewControllerClass *controller = (ViewControllerClass*)self.window.rootViewController;
or with a navigation controller:
UINavigationController *navigationController = (UINavigationController *)self.window.rootViewController;
ViewControllerClass *controller = (ViewControllerClass *)navigationController.topViewController;
And then:
controller.managedObjectContext = self.managedObjectContext;
In my favtable.m class I added this to set the managedObjectContext and it works properly.
self.managedObjectContext = ((AppDelegate *) [UIApplication sharedApplication].delegate).managedObjectContext;
Related
This is the error that sends me
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '+entityForName: nil is not a legal NSManagedObjectContext parameter searching for entity name 'Concepto''
These are my codes CoreDataStack.h
#import "NewsManager.h"
#import "CoreData/CoreData.h"
#import <sqlite3.h>
#import Foundation;
#import CoreData;
#interface CoreDataStack : NSObject
//propiedades
#property(strong, nonatomic)NSManagedObjectContext *managedObjectContext;
#property(strong, nonatomic)NSManagedObjectModel *managedObjectModel;
#property(strong, nonatomic)NSPersistentStoreCoordinator *persistentStoreCoordinator;
#property (strong, nonatomic) UIWindow *window;
//Metodos
-(void)saveContext;
-(NSURL *)applicationDocumentsDirectory;
#end
These are my codes CoreDataStack.m
#import "CoreDataStack.h"
#implementation CoreDataStack
#synthesize window = _window;
#synthesize managedObjectContext = _managedObjectContext;
#synthesize managedObjectModel = _managedObjectModel;
#synthesize persistentStoreCoordinator = _persistentStoreCoordinator;
#define MODEL_NAME #"Model"
#pragma mark - Core Data stack
-(NSManagedObjectContext *)ManagedObjectContext
{
if (_managedObjectContext != nil)
{
return _managedObjectContext;
}
//Pedir una NSPersistentStoreCoordinator()
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil)
{
_managedObjectContext = [[NSManagedObjectContext alloc] init];
[_managedObjectContext setPersistentStoreCoordinator:coordinator];
}
return _managedObjectContext;
}
//Devuelve el coordinador de almacenamiento persistente para la aplicación.
//Si el coordinador no existe, se crea y la tienda de la aplicación añade a la misma.
-(NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
if (_persistentStoreCoordinator != nil)
{
return _persistentStoreCoordinator;
}
//NSString *pathString = [NSString stringWithFormat:#"%#Model.sqlite", MODEL_NAME];
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:#"Model.splite"];
NSError *error = nil;
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
//NSDictionary *options = #{NSMigratePersistentStoresAutomaticallyOption:#YES, NSInferMappingModelAutomaticallyOption:#YES};
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:nil])
{
NSLog(#"error sin resolver %#, %#", error, [error userInfo]);
abort();
}
return _persistentStoreCoordinator;
}
-(NSManagedObjectModel *)managedObjectModel
{
if (_managedObjectModel != nil)
{
return _managedObjectModel;
}
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:#"Model" withExtension:#"momd"];
_managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return _managedObjectModel;
}
- (void)saveContext
{
NSError *error = nil;
NSManagedObjectContext *manegedObjectContext = self.managedObjectContext;
if (manegedObjectContext != nil)
{
if ([manegedObjectContext hasChanges] && ![manegedObjectContext save:&error])
{
NSLog(#"Unresolved error %#, %#",error,[error userInfo]);
abort();
}
}
}
These are my codes ModelUtil.h
#import <UIKit/UIKit.h>
#import "IPhoneSigninViewController.h"
#import "BaseSigninViewController.h"
#import "Concepto.h"
#interface ModelUtil : BaseSigninViewController <ADDConceptos>
#property (strong, nonatomic) NSFetchedResultsController *fetchedResultsController;
#property (strong, nonatomic) NSManagedObjectContext *managedObjectContext;
#end
These are my codes ModelUtil.m
#import "Concepto.h"
#import "ModelUtil.h"
#implementation ModelUtil
#synthesize fetchedResultsController = __fetchedResultsController;
#synthesize managedObjectContext = __managedObjectContext;
-(void)setupFetchedResultsController
{
// 1 - Decida lo que quiere la Entidad
NSString *entityName = #"Concepto";
// Ponga su nombre de la entidad aquí
NSLog(#"Configuración de un Controlador de resultados recuperados de la Entidad con nombre%#", entityName);
// 2 - Solicitar que la Entidad
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:entityName];
// 4 - ordena los datos que se recupera
request.sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:#"dato1, dato2"
ascending:YES
selector:#selector(localizedCaseInsensitiveCompare:)]];
self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request
managedObjectContext:self.managedObjectContext
sectionNameKeyPath:nil
cacheName:nil];
}
-(void)prepareForSegue:(UIStoryboardPopoverSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:#"Add Concepto Segue"]) {
NSLog(#"ddddddd");
IPhoneSigninViewController *addIPhoneSigninViewController = segue.destinationViewController;
addIPhoneSigninViewController.delegate = self;
addIPhoneSigninViewController.managedObjectContext = self.managedObjectContext;
}
}
-(void)theSaveButtonOnTheAddRoleTVCWasTapped:(IPhoneSigninViewController *)controller
{
[controller.navigationController popToRootViewControllerAnimated:YES];
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[self setupFetchedResultsController];
}
#end
These are my codes IPhoneSigninViewController.h
//
#import "BaseSigninViewController.h"
#import <UIKit/UIKit.h>
#import "Concepto.h"
#class IPhoneSigninViewController;
#protocol ADDConceptos <NSObject>
- (void)theSaveButtonOnTheAddRoleTVCWasTapped:(IPhoneSigninViewController *)controller;
#end
#interface IPhoneSigninViewController : BaseSigninViewController <UITextFieldDelegate, UIAlertViewDelegate>
#property (nonatomic, weak)id <ADDConceptos> delegate;
- (IBAction)signinButton:(id)sender;
- (IBAction)signinCancel:(id)sender;
#property (weak, nonatomic) IBOutlet UITextField *password;
#property (weak, nonatomic) IBOutlet UITextField *email;
#property (weak, nonatomic) IBOutlet UINavigationBar *navigationBar;
#property (weak, nonatomic) IBOutlet UINavigationItem *NavigationItem;
#property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
#property (weak, nonatomic) IBOutlet UIView *formView;
#property (weak, nonatomic) IBOutlet UIButton *signupButton;
#property (weak, nonatomic) IBOutlet UIButton *remindButton;
- (void)resignOnTap:(id)iSender;
#property (strong, nonatomic) NSManagedObjectContext *managedObjectContext;
#end
These are my codes IPhoneSigninViewController.m
//Guardar el email en el coredata
#pragma mark Guardar El usuario en el core data
-(void)SaveUsername
{
Concepto *cont = [NSEntityDescription insertNewObjectForEntityForName:#"Concepto" inManagedObjectContext:self.managedObjectContext];
cont.dato1 = email.text;
cont.dato2 = password.text;
[self.managedObjectContext save:nil];
[self.delegate theSaveButtonOnTheAddRoleTVCWasTapped:self];
[self SaveUsername];
}
#pragma mark Boton de inicio de secion
-(void)signinButton:(id)sender
{
NSLog(#"guardar datotes");
[self SaveUsername];
[self signInProcess];
}
one of those who already have more experience in ios I can explain how to fix the error ....
I am not sure what you are trying to achieve with these two lines -
self.managedObjectContext = [[[segue destinationViewController]viewControllers] objectAtIndex:0];
[[segue destinationViewController]setManagedObjectContext:self.managedObjectContext];
but I am fairly certain they will have the effect of setting both the current view controller and the destination view controller's managedObjectContext properties to nil or possibly to an instance of a UIViewController which is not right either. Delete these lines.
Also, by convention, variables start with a lower-case letter, so you should have -
IPhoneSigninViewController *addIPhoneSigninViewController = segue.destinationViewController;
addIPhoneSigninViewController.delegate = self;
addIPhoneSigninViewController.managedObjectContext = self.managedObjectContext;
I don't know why this code error.
Please help.
I read some articles and I think the problem is about context.
What Should I do?
This program is about shows data in coredata to label in viewcontroller.
AppDelegate.h
#import <UIKit/UIKit.h>
#import <CoreData/CoreData.h>
#interface AppDelegate : UIResponder <UIApplicationDelegate>
#property (strong, nonatomic) UIWindow *window;
#property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
#property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
#property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;
- (void)saveContext;
- (NSURL *)applicationDocumentsDirectory;
#end
AppDelegate.m
#import "AppDelegate.h"
#import "Test.h"
#import "ViewController.h"
#interface AppDelegate ()
#end
#implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
NSManagedObjectContext *context = [self managedObjectContext];
Test *t = [NSEntityDescription insertNewObjectForEntityForName:#"Test"
inManagedObjectContext:context];
t.name = #"please";
return YES;}
ViewController.h
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController
#property (weak, nonatomic) IBOutlet UILabel *label;
#property (nonatomic,strong) NSArray *temp;
#property (nonatomic,strong) NSManagedObjectContext* managedObjectContext;
#end
ViewController.m
#import "ViewController.h"
#import "Test.h"
#interface ViewController ()
#end
#implementation ViewController
#synthesize managedObjectContext;
#synthesize temp;
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription
entityForName:#"Test"
inManagedObjectContext:managedObjectContext];
[fetchRequest setEntity:entity];
NSError *error;
self.temp = [managedObjectContext executeFetchRequest:fetchRequest error:&error];
for(Test *info in temp){
_label.text = info.name;
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
Test.h
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
#interface Test : NSManagedObject
#property (nonatomic, retain) NSString * name;
#end
Test.m
#import "Test.h"
#implementation Test
#dynamic name;
#end
I don't know why this code error.
Please help.
I read some articles and I think the problem is about context.
What Should I do?
In your view controller, replace the line:
#synthesize managedObjectContext;
With this:
- (NSManagedObjectContext *) managedObjectContext {
return ((AppDelegate *)[[UIApplication sharedApplication] delegate]).managedObjectContext;
}
Instead of storing another, different object context in your view controller, this property will return the object context that you set up in the app delegate.
There are other ways to do this, such as creating a Core Data helper class following the Singleton pattern (as #NewYork167 suggests), but this should at least solve your current problem.
For any future reference, you can also try subclassing the NSManagedObjectContext like this:
#interface MyManagedObjectContext : NSManagedObjectContext
+ (MyManagedObjectContext *)mainThreadContext;
#end
#implementation MyManagedObjectContext
+ (MyManagedObjectContext *)mainThreadContext;
{
static MyManagedObjectContext *moc;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
moc = [[self alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
// Setup persistent store coordinator here
});
return moc;
}
#end
Reference: Best practices for passing NSManagedObjectContext around to UITabBarController child view controllers?
[self.managedObjectContext deletedObjects:lastPoint];
This line shows me an error
No visible #interface for 'NSManagedObjectContext' declares the selector 'deletedObjects'.
Here is my code
can any one solve this?
Appdelegate.h
#import <UIKit/UIKit.h>
#import <CoreData/CoreData.h>
#interface AppDelegate : UIResponder <UIApplicationDelegate>
#property (strong, nonatomic) UIWindow *window;
#property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
#property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
#property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;
- (void)saveContext;
- (NSURL *)applicationDocumentsDirectory;
#end
Appdelegate.m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
/* crete the fetch request first*/
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]initWithEntityName:#"Rectangle"];
NSError *requestError = nil;
/*And execute the fetch request on the context*/
NSArray *rectangle = [self.managedObjectContext executeFetchRequest:fetchRequest error:&requestError];
/*make sure we get the array*/
if ([rectangle count] > 0) {
/*delete the last person in the array*/
Rectangle *lastPoint = [rectangle lastObject];
[self.managedObjectContext deletedObjects:lastPoint];
if ([lastPoint isDeleted]) {
NSLog(#"Successfully deleted the last point...");
NSError *savingError = nil;
if ([self.managedObjectContext save:&savingError]) {
NSLog(#"successfully saved the context");
} else {
NSLog(#"Failed to save the context");
}
} else {
NSLog(#"Failed to delete the last point");
}
} else {
NSLog(#"Could not find any rectangle entities in the context.");
}
return YES;
}
The error message
No visible #interface for 'NSManagedObjectContext' declares the
selector 'deletedObjects'.
tells you that the class NSManagedObjectContext doesn't implement the method deletedObjects. You can check this in the API documentation.
You can use deleteObject: to delete single objects. So change your code to:
[self.managedObjectContext deleteObject:lastPoint];
As the documentation says deletedObjects is the read only property, so it has only getter method without any parameters
So you should access it just by using next
self.managedObjectContext.deletedObjects
Im new to Objective-C and CoreData and want to learn it and im trying in Xcode 5, im trying to make this tutorial.
I have followed it with some other CoreData table name, but i get some errors with my "ViewController.m" and dont know what to changes, i can see it recomment to changes "NSEntityDescription" to "kSetAttrDescription" but dont know if thats right or wrong to do, hope someone can tell mewhat to do - so i know it next time.
Error issues
Error Descriptions
My ViewController.m code.
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
//Save data as CoreData, to CoreData Table "Kunder" field "navn", "adresse", "alder" from textfield _name.text, _adress.text, _age.text.
- (IBAction)saveData:(id)sender {
AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSManagedObject *newContact;
newContact = [NSEntityDescription insertNewObjectForEntityForName:#"Kunder" inManagedObjectContext:context];
[newContact setValue: _name.text forKey:#"navn"];
[newContact setValue: _adress.text forKey:#"adresse"];
[newContact setValue: _age.text forKey:#"alder"];
//if textfield empty, then error else save and show label message "Kunde Gemt".
_name.text = #"";
_adress.text = #"";
_age.text = #"";
NSError *error;
[context save:&error];
_status.text = #"Kunde Gemt";
}
//Find-search for user by name.
- (IBAction)findKunde:(id)sender {
AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSEntityDescription *entityDesc = [NSEntityDescription entityForName:#"Kunder" inManagedObjectContext:context];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entityDesc];
NSPredicate *pred =
[NSPredicate predicateWithFormat:#"(navn = %#)", _name.text];
[request setPredicate:pred];
NSManagedObject *matches = nil;
//if no user then error, else take name match and get "adresse" and "alder" from CoreData and show it in the text fields _adress.text and _age.text and show matche count in status label.
NSError *error;
NSArray *objects = [context executeFetchRequest:request error:&error];
if ([objects count] == 0) {
_status.text = #"Ingen fundet";
} else {
matches = objects[0];
_adress.text = [matches valueForKey:#"adresse"];
_age.text = [matches valueForKey:#"alder"];
_status.text = [NSString stringWithFormat: #"%lu antal fundet", (unsigned long)[objects count]];
}
}
#end
My ViewController.h page (no error)
#import <UIKit/UIKit.h>
#import "AppDelegate.h"
#interface ViewController : UIViewController
#property (strong, nonatomic) IBOutlet UITextField *name;
#property (strong, nonatomic) IBOutlet UITextField *adress;
#property (strong, nonatomic) IBOutlet UITextField *age;
#property (strong, nonatomic) IBOutlet UILabel *status;
- (IBAction)saveData:(id)sender;
- (IBAction)findKunde:(id)sender;
#end
My AppDelegate.m file
#import "AppDelegate.h"
#implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
return YES;
}
....
#end
UPDATE
When adding text to the fields and hit save, i don get a "Save ok" message it jump to xcode and show me this.
Is seems that you forgot to import <CoreData/CoreData.h>.
You can add the import to your precompiled header (...-Prefix.pch) file
which would look similar to this:
#import <Availability.h>
#ifndef __IPHONE_5_0
#warning "This project uses features only available in iOS SDK 5.0 and later."
#endif
#ifdef __OBJC__
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h> // <-- Add this !!
#endif
You might also have to add the "CoreData.framework" to the "Link Binary With Libraries"
section of the targets "Build Phases".
I am having trouble adding a Core Data functionality to my app.
I cannot understand why managedObjectContext is always nil (even in my AppDelegate). I know that I should be passing it from the model, but and not sure how to do this.
I get the following error:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '+entityForName: nil is not a legal NSManagedObjectContext parameter searching for entity name 'Goal''
g4tappDelegate.h
#import <UIKit/UIKit.h>
#import "Goal.h"
#class g4tPopPageViewController;
#interface g4tAppDelegate : UIResponder <UIApplicationDelegate> {
NSManagedObjectModel *managedObjectModel;
NSManagedObjectContext *managedObjectContext;
NSPersistentStoreCoordinator *persistentStoreCoordinator;
UIWindow *window;
}
- (NSManagedObjectContext *)managedObjectContext;
#property (strong, nonatomic) UIWindow *window;
#property (strong, nonatomic) g4tPopPageViewController *PopPageViewController;
#property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
#property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
#property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;
#end
g4tappDelegate.m
#import "g4tAppDelegate.h"
#import "g4tPopPageViewController.h"
#import "Goal.h"
#implementation g4tAppDelegate
NSManagedObjectContext *managedObjectContext;
#synthesize PopPageViewController;
#synthesize managedObjectContext = _managedObjectContext;
#synthesize managedObjectModel = _managedObjectModel;
#synthesize persistentStoreCoordinator = _persistentStoreCoordinator;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
NSManagedObject *newGoal;
//ERROR HERE
newGoal = [NSEntityDescription
insertNewObjectForEntityForName:#"Goal"
inManagedObjectContext:_managedObjectContext];
PopPageViewController.managedObjectContext = self.managedObjectContext;
UIStoryboard* sb = [UIStoryboard storyboardWithName:#"MainStoryboard" bundle:nil];
UIViewController* vc = [sb instantiateViewControllerWithIdentifier:#"AddGoal"];
UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:vc];
[self.window setRootViewController:navigationController];
[self.window makeKeyAndVisible];
// Override point for customization after application launch.
return YES;
}
Initialize your context first. Pass the context to the viewController instance first after creating it. Either you are missing some implementation or you didn't post it here.
Also, correct your property
#property (strong, nonatomic) PopPageViewController *g4tPopPageViewController;
- (NSManagedObjectContext *)managedObjectContext
{
if (_managedObjectContext != nil) {
return _managedObjectContext;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil) {
_managedObjectContext = [[NSManagedObjectContext alloc] init];
[_managedObjectContext setPersistentStoreCoordinator:coordinator];
}
return _managedObjectContext;
}
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
if (_persistentStoreCoordinator != nil) {
return _persistentStoreCoordinator;
}
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:#"YourStore.sqlite"];
NSError *error = nil;
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:YES],NSMigratePersistentStoresAutomaticallyOption,
[NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&error]) {
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
return _persistentStoreCoordinator;
}
// Then pass it to your other controller from your viewDidLoad
vc.managedObjectContext = _managedObjectContext;