Using core data in an existing project - iphone

I need to use core data to persist data for my project, what I have done so far compiles well, but when I actually start storing things using core data, the program just quits, and I don't know the reason. I set up all the required components for core data in the appDelegate file, and I want to store data in a viewController called DetailViewController. Here is what I have done:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
// Set the tab bar controller as the window's root view controller and display.
self.window.rootViewController = self.tabBarController;
[self.window makeKeyAndVisible];
//this is what I added, reference managedObjectContext in the detail view controller.
detailViewController = [[DetailViewController alloc] init];
detailViewController.managedObjectContext = [self managedObjectContext];
return YES;
}
All components for core data have been implemented
- (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] retain];
return managedObjectModel;
}
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
if (persistentStoreCoordinator != nil) {
return persistentStoreCoordinator;
}
NSURL *storeUrl = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory]
stringByAppendingPathComponent: #"MyProjectName.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];
}
When I try to call a method in the detail view to store data, the program quits.
-(IBAction) addItem {
Info *info = [NSEntityDescription insertNewObjectForEntityForName:#"Info"
inManagedObjectContext:managedObjectContext];
info.name = item.name;
}
item is the current object in the detail view, Info is the model class file. Do I miss something here?
Thanks!
Update:
The error message in the console is:
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '+entityForName: could not locate an NSManagedObjectModel for entity name 'Info''
But I do have a Info.xcdatamodel file in the "Resources" folder, and entity name is "Info".

Did you call [self.managedObjectContext save:&error]?
Also, perhaps your bundle loading routine does not work correctly. Try loading the managedObjectContext like this:
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:#"ModelName"
withExtension:#"momd"];
__managedObjectModel = [[NSManagedObjectModel alloc]
initWithContentsOfURL:modelURL];
return __managedObjectModel;

My guess would be that in your detail view controller you either aren't synthesizing managedObjectContext or you aren't initializing it when creating your detail view controller. Check that both of those are being done. If that doesn't solve the problem, please check the console output after the crash and post any relevant information there in an update to your question.

Related

Core Data : inserting Objects crashed in global queue [ARC - iPhone simulator 6.1]

I have a very simple Core Data demo, in which there is only one button.
When I click the 'run' button, the App creates 10,000 objects in a for-loop, which is running in the global queue.
Update for more detail : If I put the for-loop in main thread, it runs well.
Update for my intent : I know that MOC is not thread-safe, but according to the Apple doc, we can also use serial queue to access the MOC, and the serial queue uses more than one threads.
Here I create the Core Data stack:
#pragma mark - Core Data Stack
- (NSManagedObjectContext *)managedObjectContext
{
if (nil != _managedObjectContext) {
return _managedObjectContext;
}
_managedObjectContext = [[NSManagedObjectContext alloc] init];
if (self.persistentStoreCoordinator) {
[_managedObjectContext setPersistentStoreCoordinator:self.persistentStoreCoordinator];
}
return _managedObjectContext;
}
- (NSManagedObjectModel *)managedObjectModel
{
if (nil != _managedObjectModel) {
return _managedObjectModel;
}
_managedObjectModel = [NSManagedObjectModel mergedModelFromBundles:nil];
return _managedObjectModel;
}
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
if (nil != _persistentStoreCoordinator) {
return _persistentStoreCoordinator;
}
NSString *storeType = NSSQLiteStoreType;
NSString *storeName = #"model.sqlite";
NSURL *storeURL = [NSURL fileURLWithPath:[[self applicationDocumentsDirectory] stringByAppendingPathComponent:storeName]];
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:self.managedObjectModel];
NSError *error = nil;
if (![_persistentStoreCoordinator addPersistentStoreWithType:storeType
configuration:nil
URL:storeURL
options:nil
error:&error])
{
NSLog(#"Error : %#\n", [error localizedDescription]);
NSAssert1(YES, #"Failed to create store %# with NSSQLiteStoreType", [storeURL path]);
}
return _persistentStoreCoordinator;
}
#pragma mark -
#pragma mark Application's Documents Directory
- (NSString *)applicationDocumentsDirectory
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
return basePath;
}
after app has launched :
#implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
if (self.managedObjectContext) {
;
}
return YES;
}
When I click the button :
- (IBAction)runButtonDidClick:(id)sender
{
/**
* Access the moc using different threads to make deadlock.
*/
[self runSave];
}
- (void)runSave
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *moc = appDelegate.managedObjectContext;
if (moc) {
for (int j = 0; j < 10000; ++j) {
People *people = [NSEntityDescription insertNewObjectForEntityForName:#"People" inManagedObjectContext:moc];
people.name = #"noname";
}
NSLog(#"**********IN SAVE %#", [NSThread currentThread]);
NSError *error = nil;
if ([moc save:&error]) {
;
}
NSLog(#"**********OUT SAVE %#", [NSThread currentThread]);
}
});
}
For clicking the run button some times, maybe 2 or 3 or 4... It crashes
I could not figure out why...
Thanks for any help.
Core data should be always work on thread witch have moc.
the only job for performBlock and performBlockAndWait is that take care of thread safety. With it inserting to Core Data will always running in the right thread. You can define moc on whatever thread you want - performBlock always choose the right one.
So:
[self.managedObjectContext performBlock:^{
for(NSDictionary *dic in arr) {
//inserting here!
}
}];
In your case:
- (void)runSave
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *moc = appDelegate.managedObjectContext;
if (moc) {
[moc performBlock:^{
for (int j = 0; j < 10000; ++j) {
People *people = [NSEntityDescription insertNewObjectForEntityForName:#"People" inManagedObjectContext:moc];
people.name = #"noname";
}
NSError *error = nil;
if ([moc save:&error]) {
;
}
}];
}
});
}

iOS - Managed object context crashes app when launching from local notification

I have an app that creates a local notification. When the app is closed (i.e. not running or in the background), it crashes when being launched from the notification. I've managed to figure out which line is crashing the app (stated in a comment below):
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
// Override point for customization after application launch.
[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
// Initialise the main view
self.viewController = [[[ViewController alloc] initWithNibName:#"ViewController" bundle:nil] autorelease];
// Initialise a Navigation Controller
UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:self.viewController];
// Set the ViewController as the rootViewController of the window
self.window.rootViewController = nav;
// Colour the navigation bar
nav.navigationBar.tintColor = [UIColor colorWithRed:0.07f green:0.59f blue:0.94f alpha:1];
// Set the background
if (isPhone568) {
self.window.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"santa_back5.png"]];
}
else {
self.window.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"santa_back.png"]];
}
[self.window makeKeyAndVisible];
[nav release];
self.viewController.managedObjectContext = [self managedObjectContext];
application.applicationIconBadgeNumber = 0;
// Handle launching from a notification
UILocalNotification *localNotif = [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];
if (localNotif) {
NSPredicate *predicate = [NSPredicate
predicateWithFormat:#"(dateCreated like %#)",
[localNotif.userInfo objectForKey:#"dateCreated"]];
LetterViewController *letterView = [[LetterViewController alloc] initWithNibName:#"LetterViewController" bundle:nil];
// Get the letter to pass on
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription
entityForName:#"Letter" inManagedObjectContext:[self managedObjectContext]];
[fetchRequest setEntity:entity];
[fetchRequest setPredicate:predicate];
NSError *error;
//
// THIS NEXT LINE IS CRASHING THE APP
//
NSArray *letters = [[self managedObjectContext] executeFetchRequest:fetchRequest error:&error];
Letter *myLetter = [letters objectAtIndex:0];
letterView.theLetter = myLetter;
//[myLetter release];
// Pass the selected object to the new view controller.
[self.viewController.navigationController pushViewController:letterView animated:YES];
[letterView release];
[fetchRequest release];
}
return YES;
}
I am using the following 3 functions to get the managed object context, persistent store coordinator and managed object model:
//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] retain];
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];
}
Any help in solving this problem would be greatly appreciated.
Thanks in advance.
Couple of things. You appear to be using Core Data on the main thread in what you show, if so all interaction must be on this thread. You should update the code someday to use the new 'perform' API which uses blocks.
Since your localNotif code now does some heavy lifting in the launch delegate it does not return for some time and iOS may kill your app. Take that same code and put it into dispatch block posted to the main queue and it should work. Add some asserts to insure the navigation controller property exists too.
Thanks for the answer. Seems my problem was with the predicate! It doesn't like me using "like" in the where clause. I changed it to an = and it works!

error +entityForName: could not locate an NSManagedObjectModel for entity name 'Savedata''

this is my delegate.m
#import "TestSaveDataAppDelegate.h"
#import "TestSaveDataViewController.h"
#implementation TestSaveDataAppDelegate
#synthesize window = _window;
#synthesize viewController = _viewController;
#synthesize managedObjectContext = __managedObjectContext;
#synthesize managedObjectModel = __managedObjectModel;
#synthesize persistentStoreCoordinator = __persistentStoreCoordinator;
This is my NSManagedObjectContext
- (NSManagedObjectContext *)managedObjectContext
{
if (__managedObjectContext != nil) {
return __managedObjectContext;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil) {
__managedObjectContext = [[NSManagedObjectContext alloc] init];
[__managedObjectContext setPersistentStoreCoordinator:coordinator];
}
return __managedObjectContext;
}
This is my NSManagedObjectModel
- (NSManagedObjectModel *)managedObjectModel
{
if (__managedObjectModel != nil) {
return __managedObjectModel;
}
__managedObjectModel = [NSManagedObjectModel mergedModelFromBundles:nil];
return __managedObjectModel;
}
This is my NSPersistentStoreCoordinator
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
if (__persistentStoreCoordinator != nil) {
return __persistentStoreCoordinator;
}
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:#"SaveData.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;
}
In my TestSaveDataViewController.h i import my Savedata.h exactly name like inside my Model.xcdatamodeld with entity name is Savedata, attribute inside here is saveslot1 with string type.
in my TestSaveDataViewController.m
#synthesize managedObjectContext;
i have a button like this
- (IBAction)button1:(id)sender
{
// save text in textfield
Savedata *savedata = (Savedata *)[NSEntityDescription insertNewObjectForEntityForName:#"Savedata" inManagedObjectContext:managedObjectContext];
[savedata setSaveslot1:label1.text];
NSError *error;
if (![managedObjectContext save:&error]) {
// This is a serious error saying the record could not be saved.
// Advise the user to restart the application
}
}
When the button is push, the text in the textfield will save and show it label1.text
but i got this error.
+entityForName: could not locate an NSManagedObjectModel for entity name 'Savedata''
how to fix it?
i already solve my problem. i forgot to delegate it. now it works.

Why Isn't Core Data Fetching My Data?

My data for for an entity's attribute is not being fetched upon restart or not being saved before quitting (could be either case). The bottom line is, the data is not showing up in the table upon restart. I think I may need to consolidate my core data methods or move them to the app delegate file instead.
I think my core data code is all messed up, can anyone help fix it?
Let me know if you need any additional code to look at from the appdelegate.m etc.
Here is the code for my View Controller:
#import "RoutineTableViewController.h"
#import "AlertPrompt.h"
#import "Routine.h"
#import "CurlAppDelegate.h"
#implementation RoutineTableViewController
#synthesize tableView;
#synthesize eventsArray;
#synthesize managedObjectContext;
- (void)dealloc
{
[managedObjectContext release];
[eventsArray release];
[super dealloc];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
- (NSManagedObjectContext *) managedObjectContext {
if (managedObjectContext != nil) {
return managedObjectContext;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil) {
managedObjectContext = [[NSManagedObjectContext alloc] init];
[managedObjectContext setPersistentStoreCoordinator: coordinator];
}
return managedObjectContext;
}
-(void)addEvent
{
Routine *routine = (Routine *)[NSEntityDescription insertNewObjectForEntityForName:#"Routine" inManagedObjectContext:managedObjectContext];
CurlAppDelegate *curlAppDelegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [curlAppDelegate managedObjectContext];
NSManagedObject *newRoutineEntry;
newRoutineEntry = [NSEntityDescription insertNewObjectForEntityForName:#"Routine" inManagedObjectContext:context];
NSError *error = nil;
if (![managedObjectContext save:&error]) {
// Handle the error.
}
[eventsArray insertObject:routine atIndex:0];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
[self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
CurlAppDelegate *curlAppDelegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [curlAppDelegate managedObjectContext];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Routine" inManagedObjectContext:context];
[request setEntity:entity];
NSError *error = nil;
NSMutableArray *mutableFetchResults = [[context executeFetchRequest:request error:&error] mutableCopy];
if (mutableFetchResults == nil) {
// Handle the error.
}
[self setEventsArray:mutableFetchResults];
[mutableFetchResults release];
[request release];
UIBarButtonItem * addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:#selector(showPrompt)];
[self.navigationItem setLeftBarButtonItem:addButton];
[addButton release];
UIBarButtonItem *editButton = [[UIBarButtonItem alloc]initWithTitle:#"Edit" style:UIBarButtonItemStyleBordered target:self action:#selector(toggleEdit)];
self.navigationItem.rightBarButtonItem = editButton;
[editButton release];
[super viewDidLoad];
}
-(void)toggleEdit
{
[self.tableView setEditing: !self.tableView.editing animated:YES];
if (self.tableView.editing)
[self.navigationItem.rightBarButtonItem setTitle:#"Done"];
else
[self.navigationItem.rightBarButtonItem setTitle:#"Edit"];
}
-(void)showPrompt
{
AlertPrompt *prompt = [AlertPrompt alloc];
prompt = [prompt initWithTitle:#"Add Workout Day" message:#"\n \n Please enter title for workout day" delegate:self cancelButtonTitle:#"Cancel" okButtonTitle:#"Add"];
[prompt show];
[prompt release];
}
- (void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex:(NSInteger)buttonIndex
{
if (buttonIndex != [alertView cancelButtonIndex])
{
NSString *entered = [(AlertPrompt *)alertView enteredText];
if(eventsArray && entered)
{
[eventsArray addObject:entered];
[tableView reloadData];
}
}
}
- (void)viewDidUnload
{
self.eventsArray = nil;
[super viewDidUnload];
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [eventsArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellEditingStyleDelete reuseIdentifier:CellIdentifier] autorelease];
cell.textLabel.text = [self.eventsArray objectAtIndex:indexPath.row];
return cell;
}
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return NO if you do not want the specified item to be editable.
return YES;
}
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete) {
// Delete the managed object at the given index path.
NSManagedObject *eventToDelete = [eventsArray objectAtIndex:indexPath.row];
[managedObjectContext deleteObject:eventToDelete];
// Update the array and table view.
[eventsArray removeObjectAtIndex:indexPath.row];
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
// Commit the change.
NSError *error = nil;
if (![managedObjectContext save:&error]) {
// Handle the error.
}
}
}
#end
And here is the data model:
Edit:
Added PersisentStoreCoordinater Method (From App Delegate):
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
if (__persistentStoreCoordinator != nil)
{
return __persistentStoreCoordinator;
}
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:#"Curl.sqlite"];
NSError *error = nil;
__persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
if (![__persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error])
{
/*
Replace this implementation with code to handle the error appropriately.
abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.
Typical reasons for an error here include:
* The persistent store is not accessible;
* The schema for the persistent store is incompatible with current managed object model.
Check the error message to determine what the actual problem was.
If the persistent store is not accessible, there is typically something wrong with the file path. Often, a file URL is pointing into the application's resources directory instead of a writeable directory.
If you encounter schema incompatibility errors during development, you can reduce their frequency by:
* Simply deleting the existing store:
[[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil]
* Performing automatic lightweight migration by passing the following dictionary as the options parameter:
[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption, [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];
Lightweight migration will only work for a limited set of schema changes; consult "Core Data Model Versioning and Data Migration Programming Guide" for details.
*/
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
return __persistentStoreCoordinator;
}
Here's a couple of tips to fix this :
Remove all references to managedObjectContext, etc. in your RoutineViewController. Only reference the CoreData classes / properties from your AppDelegate.
Whenever you need a reference (say in your AddEvent method) reference the appropriate objects from your delegate (see code below)
When this gets more complex, you'll probably want a DataManager class that handles ALL your CoreData objects. Make it a Singleton, and you'll be able to reference it in any class. For fetching objects for display, you can then create the necessary methods in this class to retrieve these objects in a NSMutableArray
CurlAppDelegate *curlAppDelegate = [[UIApplication sharedApplication] delegate]; NSManagedObjectContext *context = [curlAppDelegate managedObjectContext];
Routine *routine = (Routine *)[NSEntityDescription insertNewObjectForEntityForName:#"Routine" inManagedObjectContext:context];
See how you're now using the context from your AppDelegate and not locally? This is important, because your app will link your xdatamodel from your Bundle into your AppDelegate on initialization.
If you're concerned about the data not being saved, or overwritten, check out your AppDelegate's - (NSPersistentStoreCoordinator *)persistentStoreCoordinator
That's where the setup happens to link to your stored database when you exit and enter the app. Here's your code (modified) in your AppDelegate that loads in the Curl.sqlite file :
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator{
if (__persistentStoreCoordinator != nil)
{
return __persistentStoreCoordinator;
}
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:#"Curl.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;
}
My guess would be that your are mixing up your managed object contexts. Inserting into one and attempting to save on another. Remove your Core Data associated methods in your view controller and just try going through your app delegate methods. The data will either then be saved correctly, or an error will be tossed by Core Data. Make sure to inspect any setup/save errors in your Core Data code.
Have you attached your core data file in your Main Bundle? There are two types of Bundle in iPhone app. Main Bundle and Application Bundle. We had a scenario something like yours. We copied the database into our main bundle and write the location of the database into our code. then it worked fine. you can check on this issue also.

Core Data iPhone - Save/Load depending on Date

I have built my application using core data but I am having trouble how to work out saving and loading.
I have a UIDatePicker. I have a UITextView.
I want to save what the user types in the UITextView. Then I want to load that text back into the UITextView if the user selects the same date they originally saved it on.
Like a calendar.
Edit
Here is my appDelegate.h
#import <UIKit/UIKit.h>
#import <CoreData/CoreData.h>
#class coreDataViewController;
#interface OrganizerAppDelegate : NSObject <UIApplicationDelegate> {
NSManagedObjectModel *managedObjectModel;
NSManagedObjectContext *managedObjectContext;
NSPersistentStoreCoordinator *persistentStoreCoordinator;
coreDataViewController *viewController;
UIWindow *window;
}
#property (nonatomic, retain, readonly) NSManagedObjectModel *managedObjectModel;
#property (nonatomic, retain, readonly) NSManagedObjectContext *managedObjectContext;
#property (nonatomic, retain, readonly) NSPersistentStoreCoordinator *persistentStoreCoordinator;
#property (nonatomic, retain) IBOutlet UIWindow *window;
#property (nonatomic, retain) IBOutlet coreDataViewController *viewController;
- (NSString *)applicationDocumentsDirectory;
#end
appDelegate.m
#import "OrganizerAppDelegate.h"
#import "coreDataViewController.h"
#implementation OrganizerAppDelegate
#synthesize window;
#synthesize viewController;
#synthesize managedObjectModel;
#synthesize managedObjectContext;
#synthesize persistentStoreCoordinator;
#pragma mark -
#pragma mark Application lifecycle
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after app launch
[window addSubview:viewController.view];
[window makeKeyAndVisible];
return YES;
}
- (void)applicationWillResignActive:(UIApplication *)application {
/*
Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
*/
}
- (void)applicationDidBecomeActive:(UIApplication *)application {
/*
Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
*/
}
/**
applicationWillTerminate: saves changes in the application's managed object context before the application terminates.
*/
- (void)applicationWillTerminate:(UIApplication *)application {
NSError *error = nil;
if (managedObjectContext != nil) {
if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
/*
Replace this implementation with code to handle the error appropriately.
abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.
*/
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
}
}
#pragma mark -
#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 *)managedObjectContext {
if (managedObjectContext != nil) {
return managedObjectContext;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil) {
managedObjectContext = [[NSManagedObjectContext alloc] init];
[managedObjectContext setPersistentStoreCoordinator:coordinator];
}
return managedObjectContext;
}
/**
Returns the managed object model for the application.
If the model doesn't already exist, it is created from the application's model.
*/
- (NSManagedObjectModel *)managedObjectModel {
if (managedObjectModel != nil) {
return managedObjectModel;
}
NSString *modelPath = [[NSBundle mainBundle] pathForResource:#"Organizer" ofType:#"momd"];
NSURL *modelURL = [NSURL fileURLWithPath:modelPath];
managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return managedObjectModel;
}
/**
Returns the persistent store coordinator for the application.
If the coordinator doesn't already exist, it is created and the application's store added to it.
*/
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
if (persistentStoreCoordinator != nil) {
return persistentStoreCoordinator;
}
NSURL *storeURL = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory] stringByAppendingPathComponent: #"Organizer.sqlite"]];
NSError *error = nil;
persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
/*
Replace this implementation with code to handle the error appropriately.
abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.
Typical reasons for an error here include:
* The persistent store is not accessible;
* The schema for the persistent store is incompatible with current managed object model.
Check the error message to determine what the actual problem was.
If the persistent store is not accessible, there is typically something wrong with the file path. Often, a file URL is pointing into the application's resources directory instead of a writeable directory.
If you encounter schema incompatibility errors during development, you can reduce their frequency by:
* Simply deleting the existing store:
[[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil]
* Performing automatic lightweight migration by passing the following dictionary as the options parameter:
[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES],NSMigratePersistentStoresAutomaticallyOption, [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];
Lightweight migration will only work for a limited set of schema changes; consult "Core Data Model Versioning and Data Migration Programming Guide" for details.
*/
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
return persistentStoreCoordinator;
}
#pragma mark -
#pragma mark Application's Documents directory
/**
Returns the path to the application's Documents directory.
*/
- (NSString *)applicationDocumentsDirectory {
return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
}
#pragma mark -
#pragma mark Memory management
- (void)dealloc {
[managedObjectContext release];
[managedObjectModel release];
[persistentStoreCoordinator release];
[window release];
[super dealloc];
}
#end
viewController.m (the bit that matters anyway, all the code around this can be ignored anyway as its irrelevant, no relation to the UIDatePicker (datePicker) or UITextView (notesView).
-(void)textViewDidEndEditing:(UITextView *)textView {
NSManagedObjectContext *context = [OrganizerAppDelegate managedObjectContext];
NSManagedObject *note = [NSEntityDescription insertNewObjectForEntityForName:#"Notes" inManagedObjectContext:context];
[note setValue:notesView.text forKey:#"text"];
[note valueForKey:#"text"];
NSError *err=nil; if (![context save:&err]) { NSLog(#"Whoops, couldn't save: %#", [err localizedDescription]); } }
NSDate *dtTemp = [pkrDate.date retain];
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:#"HH"];
hour = [[dateFormatter stringFromDate:dtTemp]intValue];
[dateFormatter setDateFormat:#"mm"];
mins = [[dateFormatter stringFromDate:dtTemp]intValue];
[dateFormatter setDateFormat:#"ss"];
sec = [[dateFormatter stringFromDate:dtTemp]intValue];
NSTimeInterval *timeInterval = [dtTemp timeIntervalSince1970];
timeInterval = timeInterval - (hour*3600+mins*60+sec);
timeStamp = [[NSDate dateWithTimeIntervalSince1970:timeInterval]retain];
- (void) dateChanged:(id)sender{
//Load...
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:#"Text" inManagedObjectContext:self.managedObjectContext];
NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
[request setEntity:entityDescription];
NSPredicate *predicate = [NSPredicate predicateWithFormat:
#"(timeStamp = %#)",datePicker.date];
[request setPredicate:predicate]; //added this line later
NSArray *array = [self.managedObjectContext executeFetchRequest:request error:&error];
//check whether the array has entrys and do something with those objects here
[monTable reloadData];
[tueTable reloadData];
[wedTable reloadData];
[thuTable reloadData];
[friTable reloadData];
}
Allright, first of all, try to understand how core data works. I think you're pretty close, but programming is all about really knowing what's going on, instead of 'kinda' knowing what's going on. The Getting started with Core Data" guide is quite instructive.
Now about your code (I don't know you're exact data-model and surrounding code, so I'm kinda guessing here). I'm assuming you have a member called 'datePicker', which refers to the datepicker that you're using.
Allright, let me see if I can quickly fix some things in your code, but do be a bit careful. I haven't read through every line of your source code, and I haven't tried compiling it, so there will probably still be errors. In the end, you'll still a thorough understanding of the code.
- (void)textViewDidEndEditing:(UITextView *)textView {
NSManagedObjectContext *context = [OrganizerAppDelegate managedObjectContext];
NSManagedObject *note = [NSEntityDescription insertNewObjectForEntityForName:#"Notes" inManagedObjectContext:context];
[note setValue:notesView.text forKey:#"text"];
// Set the timestamp as well.
[note setValue:datePicker.date forKey:#"timeStamp"];
NSError *err=nil; if (![context save:&err]) { NSLog(#"Whoops, couldn't save: %#", [err localizedDescription]); } }
/* Beware, we're just storing every edit here, without every throwing anything away. We'll try to display just the latest note in the 'dateChanged', but you might want to delete any previous notes first.*/
/* I don't think this whole dissecting and generating a date is necessary */
- (void) dateChanged:(id)sender{
//Load...
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:#"Text" inManagedObjectContext:self.managedObjectContext];
NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
[request setEntity:entityDescription];
NSPredicate *predicate = [NSPredicate predicateWithFormat:
#"(timeStamp = %#)",datePicker.date];
[request setPredicate:predicate]; //added this line later
NSArray *array = [self.managedObjectContext executeFetchRequest:request error:&error];
// Assuming that the last item in the array is the item that was added last. This might or might not be reasonable.
notesView.text = [[array lastObject] text];
[monTable reloadData];
[tueTable reloadData];
[wedTable reloadData];
[thuTable reloadData];
[friTable reloadData];
}
When ever you add or edit any object , you should save that object in MOC(ManagedObjectContect).
Here is modified Code:
-(void)textViewDidEndEditing:(UITextView *)textView{
NSManagedObjectContext *context=[YourAppDelegate managedObjectContext];
NSManagedObject *note=[NSEntityDescription insertNewObjectForEntityForName:#"Notes" inManagedObjectContext:context];
[note setValue:notesView.text forKey:#"text"];
[note valueForKey:#"text"] ;
NSError *err=nil;
if (![context save:&err]) {
NSLog(#"Whoops, couldn't save: %#", [err localizedDescription]);
}
}
Well if you have a text-entry-entity in your database, just give it an attribute of type date and choose "indexed".
Then I would start an NSFetchRequest like this:
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:#"Text"
inManagedObjectContext:self.managedObjectContext];
NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
[request setEntity:entityDescription];
NSPredicate *predicate = [NSPredicate predicateWithFormat:
#"(timeStamp = %#)",datepicker.date];
[request setPredicate:predicate]; //added this line later
NSArray *array = [self.managedObjectContext executeFetchRequest:request error:&error];
//check whether the array has entrys and do something with those objects here
when the user changes the date of the datepicker. The array will be either empty or hold your text-entries.
Though maybe you should first read through "Developing with Core Data".