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.
Hope you can, I can work it out.
EDIT:
Here is what I have going, doesn't work of course. Hope you can help further. http://b.imagehost.org/view/0307/Screen_shot_2010-11-09_at_19_43_57
EDIT 2: Ok, 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];
}