Trouble adding Core Data to a Storyboard App - ios

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;

Related

Core Data - failing to load data, entity not found

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;

managedObjectContext unrecognized selector sent to instance

I am following a tutorial to develop an iOS app. I am using core data. The first view of the app is RootViewController. All Core Data stack is on the AppDelegate file. This is the part of the code from AppDelegate.m that makes the call to the RootViewController file:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Fetch the data to see if we ought to pre-populate
NSError *error = nil;
if (![[self fetchedResultsController] performFetch:&error]) {
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
[self loadFavoriteThingsData];
RootViewController *rootViewController = (RootViewController *)[navigationController topViewController];
[rootViewController setManagedObjectContext:[self managedObjectContext]];
[window addSubview:[navigationController view]];
[window makeKeyAndVisible];
return YES;
}
Now, in another part of the app I need to open a new view Controller that is a duplicate of RootViewController, called DoneViewController, but using other NSPredicates to show other core data objects.
In RootViewController there is a button to open the MenuViewController file, from there I try to open DoneViewController using following method:
- (IBAction)doneToDoaction:(id)sender {
DoneViewController *viewController = [[DoneViewController alloc] init];
[self presentViewController:viewController animated:YES completion:nil];
}
but an exception is fired:
[MenuViewController managedObjectContext]: unrecognized selector sent to instance 0x145a0c00
2013-12-26 22:58:23.688 *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[MenuViewController managedObjectContext]: unrecognized selector sent to instance
I guess I have to pass the managedObjectContext from RootViewController to MenuViewController and then from MenuViewController to DoneViewController, but I don't know how to do it.
This is due to that you are not using NSObject class. For this you have to implement NSObject in you AppDelegate.h.Like this..
#interface AppDelegate : UIResponder <UIApplicationDelegate,NSObject>{
NSManagedObjectModel *managedObjectModel;
NSManagedObjectContext *managedObjectContext;
NSPersistentStoreCoordinator *persistentStoreCoordinator;
}
and also add the properties.
#property (nonatomic, retain, readonly) NSManagedObjectModel *managedObjectModel;
#property (nonatomic, retain, readonly) NSManagedObjectContext *managedObjectContext;
#property (nonatomic, retain, readonly) NSPersistentStoreCoordinator *persistentStoreCoordinator;
- (NSString *)applicationDocumentsDirectory;
Also add code in AppDelegate.m file...
- (NSManagedObjectContext *) managedObjectContext {
if (managedObjectContext != nil) {
return managedObjectContext;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil) {
managedObjectContext = [[NSManagedObjectContext alloc] init];
[managedObjectContext setPersistentStoreCoordinator: coordinator];
}
return managedObjectContext;
}
- (NSManagedObjectModel *)managedObjectModel {
if (managedObjectModel != nil) {
return managedObjectModel;
}
managedObjectModel = [NSManagedObjectModel mergedModelFromBundles:nil] ;
return managedObjectModel;
}
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
if (persistentStoreCoordinator != nil) {
return persistentStoreCoordinator;
}
NSURL *storeUrl = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory]
stringByAppendingPathComponent: #"<Project Name>.sqlite"]];
NSError *error = nil;
persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc]
initWithManagedObjectModel:[self managedObjectModel]];
if(![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:nil error:&error])
{
/*Error for store creation should be handled in here*/
}
return persistentStoreCoordinator;
}
- (NSString *)applicationDocumentsDirectory {
return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
}
This works for me 100%. Hope so that it work for you.
There are few solutions to do what you want.
The first is to expose the context from the application delegate as #Gyanendra commented. The second is to pass the context from controller to controller. For further references I really suggest to read PASSING AROUND A NSMANAGEDOBJECTCONTEXT ON IOS by Marcus Zarra.
Anyway, I would prefer the second solution. Passing around the context or grabbing by an instance of NSManagedObject. Based on the latter each NSManagedObjectInstance has a reference to the context has been registered in.
[managedObjectInstance managedObjectContext];
These solutions prevent to have a rigid application and avoid to pollute the application delegate.
In your case, you could just follow this approach. From RootViewController pass the context to MenuViewController and then, from the latter, pass it to DoneViewController. How?
Simple enough. Just expose properties like for the controller you are interested in (MenuViewController and DoneViewController in this case).
#property (nonatomic, strong) NSManagedObjectContext* mainContext;
that can be set as
// from RootViewController
menuViewController.mainContext = [self managedObjectContext];

Multiple xcdatamodel files in Xcode

My project(for managing students' attendance in various classes) contains 2 xkcddatamodel files, one for the semester start/end dates and the other for the course data. If you look at AppDelegate.m, I've set the modelURL to the second model. How am I supposed to create a second context for the first xkcddatamodel? I've tried the solution given here. But no dice. Xcode isn't even recognising it and is asking me to replace managedObjectContext2 with managedObjectContext. How do I fix this?
Dropbox link to the project: https://www.dropbox.com/sh/ivl6nw6nw8p9j1y/MDwYDaHVH_
Here's the AppDelegate.m
//
// AppDelegate.m
// timetable app
//
// Created by Robin Malhotra on 22/12/13.
// Copyright (c) 2013 Robin's code kitchen. All rights reserved.
//
#import "AppDelegate.h"
#import <CoreData/CoreData.h>
#implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
return YES;
}
// Explicitly write Core Data accessors
- (NSManagedObjectContext *) managedObjectContext {
if (managedObjectContext != nil) {
return managedObjectContext;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil) {
managedObjectContext = [[NSManagedObjectContext alloc] init];
[managedObjectContext setPersistentStoreCoordinator: coordinator];
}
return managedObjectContext;
}
- (NSManagedObjectModel *)managedObjectModel {
if (managedObjectModel != nil) {
return managedObjectModel;
}
// removed some code about retain here as ARC hates that
return managedObjectModel;
}
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
if (persistentStoreCoordinator != nil) {
return persistentStoreCoordinator;
}
NSURL *storeUrl = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory]
stringByAppendingPathComponent: #"Courses.sqlite"]];
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:#"ClassesAttended" withExtension:#"momd"];
managedObjectModel=[[NSManagedObjectModel alloc]initWithContentsOfURL:modelURL];
NSError *error = nil;
persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc]
initWithManagedObjectModel:[self managedObjectModel]];
if(![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType
configuration:nil URL:storeUrl options:nil error:&error]) {
/*Error for store creation should be handled in here*/
}
return persistentStoreCoordinator;
}
- (NSString *)applicationDocumentsDirectory {
return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
}
/* (...Existing Application Code...) */
-(NSArray *)getAllCourses
{
NSFetchRequest *request=[[NSFetchRequest alloc]init];
NSEntityDescription *entitydesc=[NSEntityDescription entityForName:#"Course" inManagedObjectContext:managedObjectContext];
[request setEntity:entitydesc];
NSError *error;
NSArray *fetchedCourses=[self.managedObjectContext executeFetchRequest:request error:&error];
return fetchedCourses;
}
#end
and here's the AppDelegate.h
#import <UIKit/UIKit.h>
#interface AppDelegate : UIResponder <UIApplicationDelegate>
{
NSManagedObjectModel *managedObjectModel;
NSManagedObjectContext *managedObjectContext;
NSPersistentStoreCoordinator *persistentStoreCoordinator;
}
#property (strong, nonatomic) UIWindow *window;
#property (nonatomic, readonly) NSManagedObjectModel *managedObjectModel;
#property (nonatomic, readonly) NSManagedObjectContext *managedObjectContext;
#property (nonatomic, readonly) NSPersistentStoreCoordinator *persistentStoreCoordinator;
#property (nonatomic, readonly) NSManagedObjectModel *managedObjectModel2;
#property (nonatomic, readonly) NSManagedObjectContext *managedObjectContext2;
#property (nonatomic, readonly) NSPersistentStoreCoordinator *persistentStoreCoordinator2;
- (NSString *)applicationDocumentsDirectory;
- (NSArray *)getAllCourses;
#end

Unable to pass NSManagedObjectContext to my view controller

Ok, I may be in well over my head here, but suspect I am missing something quite fundamental. I have searched on stack and other forums for help on finding a solution. I've tried all the solutions I have found but none work for my situation and I cannot see what I am missing.
I have created a CoreData app. All works fine in reading and writing data to the CoreData store using NSManagedObjectContext within my appDelegate. I have checked to see if the NSManagedObjectContext is set in my AppDelegate and it is. After passing it to my only viewController I check to see if it is set and it isn't. So that is clearly my issue. I have tried everything and cannot fathom the solution, now tired and want to go to bed. I'm pretty new to iOS, so I am sure it's something fundamental.
Here's my code as it stands.
AppDelegate.m
#import "AppDelegate.h"
#import "ViewController.h"
#import "Recipe.h"
#interface AppDelegate()
#property (nonatomic, strong) NSManagedObjectContext *managedObjectContext;
#property (nonatomic, strong) NSManagedObjectModel *managedObjectModel;
#property (nonatomic, strong) NSPersistentStoreCoordinator *persistentStoreCoordinator;
#property (nonatomic, strong) ViewController *viewController;
#end
#implementation AppDelegate
#synthesize managedObjectModel, managedObjectContext, persistentStoreCoordinator, viewController;
#synthesize window = _window;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
NSManagedObjectContext *context = [self managedObjectContext];
if (!context) {
NSLog(#"There is an error!!!");
}
if (context == nil) {
NSLog(#"Context is nil in appdelegate");
}
else {
NSLog(#"Context is set in appdelegate");
}
viewController.managedObjectContext = self.managedObjectContext;
// Override point for customization after application launch.
return YES;
}
#pragma mark - Core Data
- (NSManagedObjectModel *)managedObjectModel
{
if (managedObjectModel == nil) {
NSString *modelPath = [[NSBundle mainBundle] pathForResource:#"RecipeBook" ofType:#"momd"];
NSURL *modelURL = [NSURL fileURLWithPath:modelPath];
managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
}
return managedObjectModel;
}
- (NSString *)documentsDirectory
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return documentsDirectory;
}
- (NSString *)dataStorePath
{
return [[self documentsDirectory] stringByAppendingPathComponent:#"DataStore.sqlite"];
}
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
if (persistentStoreCoordinator == nil) {
NSURL *storeURL = [NSURL fileURLWithPath:[self dataStorePath]];
persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:self.managedObjectModel];
NSError *error;
if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
NSLog(#"Error adding persistent store %#, %#", error, [error userInfo]);
abort();
}
}
return persistentStoreCoordinator;
}
- (NSManagedObjectContext *)managedObjectContext
{
if (managedObjectContext == nil) {
NSPersistentStoreCoordinator *coordinator = self.persistentStoreCoordinator;
if (coordinator != nil) {
managedObjectContext = [[NSManagedObjectContext alloc] init];
[managedObjectContext setPersistentStoreCoordinator:coordinator];
}
}
return managedObjectContext;
}
#end
ViewController.h
#import <UIKit/UIKit.h>
#interface ViewController : UITableViewController {
NSArray *recipes;
NSManagedObjectContext *managedObjectContext;
}
#property (nonatomic, retain) NSArray *recipes;
#property (nonatomic, retain) NSManagedObjectContext *managedObjectContext;
#end
ViewController.m
#import "ViewController.h"
#import "Recipe.h"
#interface ViewController ()
#end
#implementation ViewController
#synthesize recipes;
#synthesize managedObjectContext;
- (void)viewDidLoad
{
[super viewDidLoad];
NSLog(#"View Did Load");
NSManagedObjectContext *context = [self managedObjectContext];
if (!context) {
NSLog(#"There is an error!!!");
}
if (context == nil) {
NSLog(#"Context is nil in viewController");
}
else {
NSLog(#"Context is set in viewController");
}
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
} else {
return YES;
}
}
- (void)viewDidUnload {
[super viewDidUnload];
}
#end
I know the NSManagedObjectContext is nil in my ViewController. The question is how do I pass my context from AppDelegate into ViewController? I don't want to have to question the AppDelegate from my viewControllers (More will hopefully be added) every time I want to query CoreData, I'm looking to pass the managedObjectContext around.
I hope that all makes sense. :)
I have discovered the answer to my issue. The managedObjectContext wasn't being passed correctly to my viewController.
I was using:
viewController.managedObjectContext = self.managedObjectContext;
When I should have been using:
ViewController *viewController = (ViewController *)self.window.rootViewController;
viewController.managedObjectContext = self.managedObjectContext;
Thanks user523234 for putting me on the right lines.

"window" undeclared (first use in this function) error in iOS tutorial

I am trying the Core Data Tutorial and I have copied the code as given in this Apple's tutorial on Core Data here:
http://developer.apple.com/library/ios/#documentation/DataManagement/Conceptual/iPhoneCoreData01/Articles/02_RootViewController.html
It asks us to compile and run after implementing the application delegate. When I do so, Xcode 4 compiler gives this error "window undeclared (first use in this function)". I can see that there is window declared as a property and there is a synthesize line in the code like so:
#synthesize window=_window;
so even though there is a window property declared in the program, why am I getting this error?
Here are the .h and .m files:
.h:
#import
#interface LocationsAppDelegate : NSObject <UIApplicationDelegate> {
UINavigationController *navigationController;
}
#property (nonatomic, retain) IBOutlet UIWindow *window;
#property (nonatomic, retain) UINavigationController *navigationController;
#property (nonatomic, retain, readonly) NSManagedObjectContext *managedObjectContext;
#property (nonatomic, retain, readonly) NSManagedObjectModel *managedObjectModel;
#property (nonatomic, retain, readonly) NSPersistentStoreCoordinator *persistentStoreCoordinator;
- (void)saveContext;
- (NSURL *)applicationDocumentsDirectory;
#end
Now for the .m file:
#import "LocationsAppDelegate.h"
#import "RootViewController.h"
#implementation LocationsAppDelegate
#synthesize navigationController;
#synthesize window=_window;
#synthesize managedObjectContext=__managedObjectContext;
#synthesize managedObjectModel=__managedObjectModel;
#synthesize persistentStoreCoordinator=__persistentStoreCoordinator;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
RootViewController *rootViewController = [[RootViewController alloc] initWithStyle:UITableViewStylePlain];
NSManagedObjectContext *context = [self managedObjectContext];
if(!context) {
//handle the error you dummy!!
}
rootViewController.managedObjectContext = context;
UINavigationController *aNavigationController = [[UINavigationController alloc]initWithRootViewController:rootViewController];
self.navigationController = aNavigationController;
[self.window addSubview:[navigationController view]];
[self.window makeKeyAndVisible];
[rootViewController release];
[aNavigationController release];
return YES;
}
- (void)applicationWillTerminate:(UIApplication *)application
{
[self saveContext];
}
- (void)dealloc
{
[_window release];
[__managedObjectContext release];
[__managedObjectModel release];
[__persistentStoreCoordinator release];
[super dealloc];
}
- (void)saveContext
{
NSError *error = nil;
NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
if (managedObjectContext != nil)
{
if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error])
{
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
}
}
#pragma mark - Core Data stack
- (NSManagedObjectContext *)managedObjectContext
{
if (__managedObjectContext != nil)
{
return __managedObjectContext;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil)
{
__managedObjectContext = [[NSManagedObjectContext alloc] init];
[__managedObjectContext setPersistentStoreCoordinator:coordinator];
}
return __managedObjectContext;
}
- (NSManagedObjectModel *)managedObjectModel
{
if (__managedObjectModel != nil)
{
return __managedObjectModel;
}
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:#"Locations" withExtension:#"momd"];
__managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return __managedObjectModel;
}
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
if (__persistentStoreCoordinator != nil)
{
return __persistentStoreCoordinator;
}
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:#"Locations.sqlite"];
NSError *error = nil;
__persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
if (![__persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error])
{
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
return __persistentStoreCoordinator;
}
#pragma mark - Application's Documents directory
- (NSURL *)applicationDocumentsDirectory
{
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
#end
Try to use
self.window
instead of
window
Just to expand on that answer a bit:
You can see from the #synthesize statement that the property window is backed by the instance variable _window. So you use window to access it via the getter (self.window or [self window]), but if you're trying to access the instance variable directly, it would be _window.

Resources