TTNavigator URL values do not match current VC - ios

Good day guys, I would like to inquire if anyone of you may have encountered a problem like mine. I have been working on a project using the TTNavigator of the Three20 framework. Every view is displayed and transitioned as it should be. I have an App menu that has buttons to the application's respective modules. The problem is that, when i click the button to a particular module, and when that view is displayed, the URL property value of the TTNavigator is that of the app's menu view (tt://mainMenu) and not the module's initial View (e.g. "tt://messageBoard" or "tt://profilePage"). i have checked and reviewed the necessary code blocks to which this problem may be linked to but i can't seem to fine the fault at hand.
Here's the definition for my AppDelegate
#import "Three20TestAppDelegate.h"
#import "StartViewController.h"
#import "JumpsiteProfilePage.h"
#import "MenuViewController.h"
#import "BNDefaultStylesheet.h"
#import "MessageBoardViewController.h"
#import "GroupListViewController.h"
#import "DrillDownGroupListView.h"
#import "ProfileListViewController.h"
#import "ProfileDetailsViewController.h"
#define UIColorFromRGB(rgbValue) [UIColor \
colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 \
green:((float)((rgbValue & 0xFF00) >> 8))/255.0 \
blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]
#implementation UINavigationBar (UINavigationBarCategory)
-(void)drawRect:(CGRect)rect{
UIImage *image = [UIImage imageNamed:#"NavBar BG.png"];
[image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
self.tintColor = UIColorFromRGB(0xFFD900);
}
#end
#implementation UIToolbar (UIToolbarCategory)
-(void)drawRect:(CGRect)rect{
UIImage *image = [UIImage imageNamed:#"NavBar BG.png"];
[image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
self.tintColor = UIColorFromRGB(0xFFD900);
[super drawRect:rect];
}
#end
#implementation Three20TestAppDelegate
#synthesize window=_window;
#synthesize managedObjectContext=__managedObjectContext;
#synthesize managedObjectModel=__managedObjectModel;
#synthesize persistentStoreCoordinator=__persistentStoreCoordinator;
- (void)applicationDidFinishLaunching:(UIApplication *)application {
TTNavigator *navigator = [TTNavigator navigator];
navigator.window = _window;
navigator.persistenceMode = TTNavigatorPersistenceModeAll;
navigator.supportsShakeToReload = YES;
[TTStyleSheet setGlobalStyleSheet:[[[BNDefaultStylesheet alloc] init] autorelease]];
TTURLMap *map = navigator.URLMap;
//startView(Log-in View)
[map from:#"tt://startView"
toSharedViewController:[StartViewController class]];
//Application's Menu
[map from:#"tt://mainMenu"
toSharedViewController:[MenuViewController class]];
//User's Profile module
[map from:#"tt://profilePage"
toSharedViewController:[JumpsiteProfilePage class]];
//Message Board module
[map from:#"tt://messageBoard"
toSharedViewController:[MessageBoardViewController class]];
[map from:#"tt://groupList"
toSharedViewController:[GroupListViewController class]];
[map from:#"tt://drillDownListView"
toSharedViewController:[DrillDownGroupListView class]];
//Profile List module
[map from:#"tt://profileList"
toViewController:[ProfileListViewController class]];
[map from:#"tt://profileDetailsList"
toSharedViewController:[ProfileDetailsViewController class]];
[navigator openURLAction:[TTURLAction actionWithURLPath:#"tt://startView"]];
// Override point for customization after application launch
[_window makeKeyAndVisible];
}
- (void)applicationWillResignActive:(UIApplication *)application
{
}
- (void)applicationDidEnterBackground:(UIApplication *)application
{
}
- (void)applicationWillEnterForeground:(UIApplication *)application
{
}
- (void)applicationDidBecomeActive:(UIApplication *)application
{
}
- (void)applicationWillTerminate:(UIApplication *)application
{
[self saveContext];
}
- (void)dealloc
{
[_window release];
[__managedObjectContext release];
[__managedObjectModel release];
[__persistentStoreCoordinator release];
[super dealloc];
}
- (void)awakeFromNib
{
}
- (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:#"Three20Test" withExtension:#"momd"];
__managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return __managedObjectModel;
}
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
if (__persistentStoreCoordinator != nil)
{
return __persistentStoreCoordinator;
}
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:#"Three20Test.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

Mapping ViewController
[map from:kAppRootURLPath toViewController:[HomeThumbnailViewController class]];
Call to ViewController
TTURLAction *urlAction=[[[TTURLAction alloc] initWithURLPath:strTTURL] autorelease];
urlAction.animated=YES;
[[TTNavigator navigator]openURLAction:urlAction];

Related

Why won't my model save to Core Data?

I'm quite new to Objective-C and I'm trying to mess around with Core Data. I have the following App Delegate interface and implementation:
#import <UIKit/UIKit.h>
#interface SDTAppDelegate : UIResponder <UIApplicationDelegate>
#property (strong, nonatomic) UIWindow *window;
#property (nonatomic, strong) NSManagedObjectContext *managedObjectContext;
#property (nonatomic, strong) NSManagedObjectModel *managedObjectModel;
#property (nonatomic, strong) NSPersistentStoreCoordinator *persistentStoreCoordinator;
- (void)saveManagedObjectContext;
- (NSManagedObjectContext *)setupManagedObjectContext;
- (NSManagedObjectModel *)setupManagedObjectModel;
- (NSPersistentStoreCoordinator *)setupPersistentStoreCoordinator;
- (NSURL *)applicationDocumentsDirectory;
#end
Implementation
#import "SDTAppDelegate.h"
#import "ToDoItem.h"
#implementation SDTAppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Get the managed object context and associate it to the app delegate
self.managedObjectContext = [self setupManagedObjectContext];
return YES;
}
- (void)applicationWillTerminate:(UIApplication *)application
{
[self saveManagedObjectContext];
}
/**
* Save the MOC!
*/
- (void)saveManagedObjectContext
{
NSError *error = nil;
if (self.managedObjectContext != nil)
{
if ([self.managedObjectContext hasChanges] && ![self.managedObjectContext save:&error])
{
/*
THIS NEEDS TO BE REPLACED
*/
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
}
}
#pragma mark - Core Data stack
/**
Returns the managed object context for the application.
If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application.
*/
- (NSManagedObjectContext *)setupManagedObjectContext
{
if (self.managedObjectContext != nil)
{
return self.managedObjectContext;
}
NSPersistentStoreCoordinator *coordinator = [self setupPersistentStoreCoordinator];
if (coordinator != nil)
{
self.managedObjectContext = [[NSManagedObjectContext alloc] init];
[self.managedObjectContext setPersistentStoreCoordinator:coordinator];
}
return self.managedObjectContext;
}
/**
* Return the managed object model. If it doesn't exist, create it.
*/
- (NSManagedObjectModel *)setupManagedObjectModel
{
if (self.managedObjectModel != nil)
{
return self.managedObjectModel;
}
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:#"Model" withExtension:#"momd"];
self.managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return self.managedObjectModel;
}
/**
* Return the persistent store coordinator. If it doesn't exist, create it.
*/
- (NSPersistentStoreCoordinator *)setupPersistentStoreCoordinator
{
if (self.persistentStoreCoordinator != nil)
{
return self.persistentStoreCoordinator;
}
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:#"Model.sqlite"];
NSError *error = nil;
self.persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self setupManagedObjectModel]];
if (![self.persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType
configuration:nil
URL:storeURL
options:nil
error:&error])
{
/*
THIS NEEDS TO BE REPLACED
*/
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
return self.persistentStoreCoordinator;
}
#pragma mark - Application's Documents directory
/**
* Return the URL to the application's Documents directory.
*/
- (NSURL *)applicationDocumentsDirectory
{
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
#end
And then in my controller I have the following to save a new model:
// Take the managed object context from the app delegate
SDTAppDelegate *appDelegate = (SDTAppDelegate *)[UIApplication sharedApplication].delegate;
NSManagedObjectContext *context = appDelegate.managedObjectContext;
// Add the new item
ToDoItem *newItem = [NSEntityDescription insertNewObjectForEntityForName:#"ToDoItem" inManagedObjectContext:context];
newItem.item = self.textField.text;
newItem.completed = 0;
No matter what happens I can't get the application to save. It shows up fine in the interface, but when I quit and restart the data is no longer there. I'm guessing this is something wrong with my persistent storage?
You should save the context in order to save in the persistent store.
NSError *error;
[context save:&error];
Hope it helps. Cheers

Core-Data : Data is not been saved up

while following the ebook of http://timroadley.com/ i am inserting. but when i check in sqlite their is no data present in it.also i have used -com.apple.CoreData.SQLDebug to debug but no query is being shown.Source Code
Solution:- Data will only show in sqlite when i will terminate the app or the app will go in background after pressing home button.
AppDelegate.h
#import <UIKit/UIKit.h>
#import "CoreDataHelper.h"
#import <CoreData/CoreData.h>
#interface AppDelegate : UIResponder <UIApplicationDelegate>
#property (strong, nonatomic) UIWindow *window;
#property (nonatomic, strong, readonly) CoreDataHelper *coreDataHelper;
#end
AppDelegate.m
- (void)demo {
NSArray *newItemNames = [NSArray arrayWithObjects:
#"Apples", #"Milk", #"Bread", #"Cheese", #"Sausages", #"Butter", #"Orange Juice", #"Cereal", #"Coffee", #"Eggs", #"Tomatoes", #"Fish", nil];
for (NSString *newItemName in newItemNames) {
Item *newItem =
[NSEntityDescription insertNewObjectForEntityForName:#"Item" inManagedObjectContext:_coreDataHelper.context];
newItem.name = newItemName;
NSLog(#"Inserted New Managed Object for '%#'", newItem.name);
}
}
- (CoreDataHelper*)cdh {
if (!_coreDataHelper) {
_coreDataHelper = [CoreDataHelper new];
[_coreDataHelper setupCoreData];
}
return _coreDataHelper;
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
return YES;
}
- (void)applicationDidEnterBackground:(UIApplication *)application
{
[[self cdh] saveContext];
}
- (void)applicationDidBecomeActive:(UIApplication *)application
{
[self cdh];
[self demo];
}
- (void)applicationWillTerminate:(UIApplication *)application
{
[[self cdh] saveContext];
}
CoreDataHelper.h
#property(nonatomic,readonly) NSManagedObjectContext *context;
#property(nonatomic,readonly) NSManagedObjectModel *model;
#property(nonatomic,readonly) NSPersistentStore *store;
#property(nonatomic,readonly) NSPersistentStoreCoordinator *coordinator;
-(void)setupCoreData;
-(void)saveContext;
CoreDataHelper.m
#pragma mark - FILES
NSString *storeFilename = #"Grocery-Dude.sqlite";
#pragma mark - PATHS
- (NSString *)applicationDocumentsDirectory {
return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES) lastObject];
}
- (NSURL *)applicationStoresDirectory {
NSURL *storesDirectory =
[[NSURL fileURLWithPath:[self applicationDocumentsDirectory]]
URLByAppendingPathComponent:#"Stores"];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:[storesDirectory path]]) {
NSError *error = nil;
if ([fileManager createDirectoryAtURL:storesDirectory
withIntermediateDirectories:YES
attributes:nil
error:&error]) {
}
else {
NSLog(#"FAILED to create Stores directory: %#", error);}
}
return storesDirectory;
}
- (NSURL *)storeURL {
return [[self applicationStoresDirectory]
URLByAppendingPathComponent:storeFilename];
}
#pragma mark - SETUP
- (id)init {
self = [super init];
if (!self) {return nil;}
_model = [NSManagedObjectModel mergedModelFromBundles:nil];
_coordinator = [[NSPersistentStoreCoordinator alloc]
initWithManagedObjectModel:_model];
_context = [[NSManagedObjectContext alloc]
initWithConcurrencyType:NSMainQueueConcurrencyType];
[_context setPersistentStoreCoordinator:_coordinator];
return self;
}
- (void)loadStore {
if (_store) {return;} // Don’t load store if it's already loaded
NSDictionary *options =
#{NSSQLitePragmasOption: #{#"journal_mode": #"DELETE"}};
NSError *error = nil;
_store = [_coordinator addPersistentStoreWithType:NSSQLiteStoreType
configuration:nil
URL:[self storeURL]
options:options error:&error];
if (!_store) {NSLog(#"Failed to add store. Error: %#", error);abort();}
else {NSLog(#"Successfully added store: %#", _store);}
}
- (void)setupCoreData {
[self loadStore];
}
#pragma mark - SAVING
- (void)saveContext {
if ([_context hasChanges]) {
NSError *error = nil;
if ([_context save:&error]) {
NSLog(#"_context SAVED changes to persistent store");
} else {
NSLog(#"Failed to save _context: %#", error);
}
} else {
NSLog(#"SKIPPED _context save, there are no changes!");
}
}
Try saving item in the loop itself like
NSArray *newItemNames = [NSArray arrayWithObjects:
#"Apples", #"Milk", #"Bread", #"Cheese", #"Sausages", #"Butter", #"Orange Juice", #"Cereal", #"Coffee", #"Eggs", #"Tomatoes", #"Fish", nil];
for (NSString *newItemName in newItemNames) {
Item *newItem =
[NSEntityDescription insertNewObjectForEntityForName:#"Item" inManagedObjectContext:_coreDataHelper.context];
newItem.name = newItemName;
NSLog(#"Inserted New Managed Object for '%#'", newItem.name);
[[self cdh] saveContext];
}

Core data entity array generate crash on release or remove objects in IOS

This is my CoreDataManagerClass.
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
#interface RTC_CoreDataManager : NSObject
#property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
#property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
#property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;
- (void)saveContext;
- (NSURL *)applicationDocumentsDirectory;
-(void)insertEntity:(NSString *)entityName arrayOfManagedObject:(NSMutableArray *)array;
+(RTC_CoreDataManager *)shredInstance;
#end
#import "RTC_CoreDataManager.h"
RTC_CoreDataManager *obj_RTC;
#implementation RTC_CoreDataManager
#synthesize managedObjectContext = __managedObjectContext;
#synthesize managedObjectModel = __managedObjectModel;
#synthesize persistentStoreCoordinator = __persistentStoreCoordinator;
- (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();
}
}
}
+(RTC_CoreDataManager *)shredInstance{
if (obj_RTC == nil) {
obj_RTC = [[RTC_CoreDataManager alloc]init];
}
return obj_RTC;
}
#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:#"RTC" withExtension:#"momd"];
__managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return __managedObjectModel;
}
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
if (__persistentStoreCoordinator != nil) {
return __persistentStoreCoordinator;
}
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:#"RTC.sqlite"];
NSError *error = nil;
if (![[NSFileManager defaultManager] copyItemAtURL:storeURL toURL:[NSURL alloc] error:&error]) {
NSLog(#"Oops, could copy preloaded data");
}
__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
// Returns the URL to the application's Documents directory.
- (NSURL *)applicationDocumentsDirectory
{
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
-(void)insertEntity:(NSString *)entityName arrayOfManagedObject:(NSMutableArray *)array
{
NSManagedObjectContext *backgroundMOC = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
for (id object in array)
{
[backgroundMOC performBlockAndWait:^
{
NSError *error;
if (![__managedObjectContext save:&error])
{
NSLog(#"Whoops, couldn't save: %#", [error localizedDescription]);
}
}];
}
}
#end
And this is my code in another controller.
-(void)viewDidLoad
{
[super viewDidLoad];
appDele_Obj = (RTC_AppDelegate *)[[UIApplication sharedApplication] delegate];
appDele_Obj.entityArray=[[NSMutableArray alloc]init];
for (int i=0; i<10; i++)
{
Survey *objSurvey = [NSEntityDescription
insertNewObjectForEntityForName:#"Survey"
inManagedObjectContext:[RTC_CoreDataManager shredInstance].managedObjectContext]; [objSurvey setFirstName:#"1"];
[objSurvey setLastName:#"2"];
[objSurvey setEmpId:#"3"];
[objSurvey setLanguage:#"Hindi"];
[objSurvey setCountry:#"India"];
[objSurvey setSurveyNo:[NSNumber numberWithInt:2]];
[[appDele_Obj entityArray] addObject:objSurvey];
[objSurvey release];
}
//[objSurvey release];
[[RTC_CoreDataManager shredInstance] insertEntity:#"Survey" arrayOfManagedObject:[appDele_Obj entityArray]];
if ([[appDele_Obj entityArray]count] >0) {
[[appDele_Obj entityArray] removeAllObjects];
}
}
So My question is,
If I call method removeAllObjects on [appDele_Obj entityArray] crashing the application. Why I can not call [[appDele_Obj entityArray] removeAllObjects];
in above approach. Any one can help me to solve this crash.
Thanks.
It's a simple case of memory mis-management. This creates an autoreleased object:
Survey *objSurvey = [NSEntityDescription
insertNewObjectForEntityForName:#"Survey"
inManagedObjectContext:[RTC_CoreDataManager shredInstance].managedObjectContext];
Then you do this:
[[appDele_Obj entityArray] addObject:objSurvey];
[objSurvey release];
You should not be calling release here. The object is autoreleased-- calling release is not only unnecessary, it's dangerous. Later on when you remove the objects from the array, you end up over-releasing every object in it. That causes the crash.
A few other things from the code:
Calling save: on a managed object context in a loop is unnecessary unless you're making new changes on each pass through the loop. Your insertEntity:arrayOfManagedObject: method is doing a lot of unnecessary work.
The array in viewDidLoad is not necessary or useful for what you're doing. You've created the objects, and they're in the managed object context. Once you finish setting the attributes of those objects, you don't need to keep references. Keep adding objects until you're done, then tell the managed object context to save.
It's a minor detail, but you named a method that creates a singleton shredInstance. "Shred" is almost exactly the opposite of what you're doing in that method. You probably meant sharedInstance.

managedObjectContext is nil

I'm trying to add Core Data to an existing project. I've:
1)added the Core Data framework
2)added the accessors and properties to the AppDelegate
3)created the data model file
Now when I try to call
NSManagedObjectContext *context = [self managedObjectContext];
from a view controller the context is nil and the managedObjectContext never fires.
Here is the AppDelegate:
#import "XXXAppDelegate.h"
#import <CoreData/CoreData.h>
#implementation XXXAppDelegate
#synthesize window=_window;
#synthesize navigationController=_navigationController;
#synthesize managedObjectContext = _managedObjectContext;
#synthesize managedObjectModel = _managedObjectModel;
#synthesize persistentStoreCoordinator = _persistentStoreCoordinator;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
// Add the navigation controller's view to the window and display.
self.window.rootViewController = self.navigationController;
[self.window makeKeyAndVisible];
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;
}
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];
}
#end
EDIT: here is my view controller code
NSManagedObjectContext *context = [self managedObjectContext];
NSManagedObject *cardSet = [NSEntityDescription insertNewObjectForEntityForName:#"CardSet" inManagedObjectContext:context];
[cardSet setValue:#"Set 1" forKey:#"cardSetName"];
Try adding these condition to check if your managedObjectContext is nil or not wherever you want to use it. If its nil copy it from Appdelegate file.
if (managedObjectContext == nil)
{
managedObjectContext = [(AppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
NSLog(#"After managedObjectContext: %#", managedObjectContext);
}
Assuming your properties are declared... you are synthesizing them to ivars with an underscore in front. That's a good thing. However, the only place you want to access them with the underscore is in the implementation of the getter/setter for the property. Unfortunately, that's not happening in any of these. Change it to...
- (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;
}
If you look at the Master-Detail Application template in Xcode you see they pass the ManagedObjectContext in the AppDelegate like this:
#import "AppDelegate.h"
#import "MasterViewController.h"
#implementation AppDelegate
#synthesize managedObjectContext = _managedObjectContext;
#synthesize managedObjectModel = _managedObjectModel;
#synthesize persistentStoreCoordinator = _persistentStoreCoordinator;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
UINavigationController *navigationController = (UINavigationController *)self.window.rootViewController;
MasterViewController *controller = (MasterViewController *)navigationController.topViewController;
NSLog(#"navigationController viewControllers: %#",[navigationController viewControllers]);
NSLog(#"navigationController.topViewController: %#",navigationController.topViewController);
controller.managedObjectContext = self.managedObjectContext;
return YES;
}
If you need a TabBarViewController in front of your app the code looks like this:
#import "AppDelegate.h"
#import "MasterViewController.h"
#implementation AppDelegate
#synthesize managedObjectContext = _managedObjectContext;
#synthesize managedObjectModel = _managedObjectModel;
#synthesize persistentStoreCoordinator = _persistentStoreCoordinator;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
UITabBarController *tabController = (UITabBarController *)self.window.rootViewController;
UINavigationController *navigationController = (UINavigationController *)[[tabController viewControllers] objectAtIndex:0];
MasterViewController *controller = (MasterViewController *)[[navigationController viewControllers] objectAtIndex:0];
controller.managedObjectContext = self.managedObjectContext;
navigationController = (UINavigationController *)[[tabController viewControllers] objectAtIndex:1];
controller = (MasterViewController *)[[navigationController viewControllers] objectAtIndex:0];
controller.managedObjectContext = self.managedObjectContext;
navigationController = (UINavigationController *)[[tabController viewControllers] objectAtIndex:2];
controller = (MasterViewController *)[[navigationController viewControllers] objectAtIndex:0];
controller.managedObjectContext = self.managedObjectContext;
return YES;
}
I don't know how you got past without compiler errors, but your #synthesizes use underscore'd variables that your getters never access. Do it like this:
- (NSManagedObjectContext *) managedObjectContext {
if (_managedObjectContext != nil) {
return _managedObjectContext;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil) {
_managedObjectContext = [[NSManagedObjectContext alloc] init];
[_managedObjectContext setPersistentStoreCoordinator: coordinator];
}
return _managedObjectContext;
}
Take note of _managedObjectContext (with underscore). Do the same fixes with managedObjectModel and persistentStoreCoordinator.

"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