Core Data iPhone - Save/Load depending on Date - iphone

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".

Related

No data in SQLite [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I have this book about Core Data. I am on my second chapter and there's an ongoing project that I followed. The project adds an Organization, and three employees. One of the employee is a leader. I have successfully followed the steps, although there are 4 warnings but it doesn't have an error. I know this should work because I had this same project before I reinstall my OSX.
AppDelegate.h
#import <UIKit/UIKit.h>
#import <CoreData/CoreData.h>
#class ViewController;
#interface AppDelegate : UIResponder <UIApplicationDelegate>
#property (strong, nonatomic) UIWindow *window;
#property (strong, nonatomic) ViewController *viewController;
//Core Data Implementation
#property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
#property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
#property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;
- (void)saveContext;
- (NSURL *)applicationDocumentsDirectory;
//Display Person
- (void)readData;
- (void)displayPerson:(NSManagedObject *)person withIndentation:(NSString *)indentation;
#end
AppDelegate.m
#import "AppDelegate.h"
#import "ViewController.h"
#implementation AppDelegate
#synthesize managedObjectContext = _managedObjectContext;
#synthesize managedObjectModel = _managedObjectModel;
#synthesize persistentStoreCoordinator = _persistentStoreCoordinator;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[self createData];
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
self.viewController = [[ViewController alloc] initWithNibName:#"ViewController" bundle:nil];
self.window.rootViewController = self.viewController;
[self.window makeKeyAndVisible];
return YES;
}
#pragma mark - Create Data
-(void)createData
{
NSManagedObject *organization = [NSEntityDescription insertNewObjectForEntityForName:#"Organization" inManagedObjectContext:self.managedObjectContext];
[organization setValue:#"Company, Inc." forKey:#"name"];
[organization setValue:[NSNumber numberWithInt:[#"Company, Inc." hash]] forKey:#"id"];
NSManagedObject *john = [NSEntityDescription insertNewObjectForEntityForName:#"Person" inManagedObjectContext:self.managedObjectContext];
[john setValue:#"John" forKey:#"name"];
[john setValue:[NSNumber numberWithInt:[#"John" hash]] forKey:#"id"];
NSManagedObject *jane = [NSEntityDescription insertNewObjectForEntityForName:#"Person" inManagedObjectContext:self.managedObjectContext];
[jane setValue:#"Jane" forKey:#"name"];
[jane setValue:[NSNumber numberWithInt:[#"Jane" hash]] forKey:#"id"];
NSManagedObject *bill = [NSEntityDescription insertNewObjectForEntityForName:#"Person" inManagedObjectContext:self.managedObjectContext];
[bill setValue:#"Bill" forKey:#"name"];
[bill setValue:[NSNumber numberWithInt:[#"Bill" hash]] forKey:#"id"];
NSMutableSet *johnsEmployees = [john mutableSetValueForKey:#"employees"];
[johnsEmployees addObject:jane];
[johnsEmployees addObject:bill];
}
- (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:#"Core01" withExtension:#"momd"];
_managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return _managedObjectModel;
}
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
if (_persistentStoreCoordinator != nil) {
return _persistentStoreCoordinator;
}
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:#"Core01.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];
}
#pragma mark - Display Person
- (void)displayPerson:(NSManagedObject*)person withIndentation:(NSString*)indentation {
NSLog(#"%#Name: %#", indentation, [person valueForKey:#"name"]);
indentation = [NSString stringWithFormat:#"%# ", indentation];
NSSet *employees = [person valueForKey:#"employees"];
id employee;
NSEnumerator *it = [employees objectEnumerator];
while ((employee = [it nextObject]) != nil) {
[self displayPerson:employee withIndentation:indentation];
}
}
- (void)readData {
NSManagedObjectContext *context = [self managedObjectContext];
NSEntityDescription *orgEntity = [NSEntityDescription entityForName:#"Organization" inManagedObjectContext:context];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
[fetchRequest setEntity:orgEntity];
NSArray *organizations = [context executeFetchRequest:fetchRequest error:nil];
id organization;
NSEnumerator *it = [organizations objectEnumerator];
while ((organization = [it nextObject]) != nil) {
NSLog(#"Organization: %#", [organization valueForKey:#"name"]);
NSManagedObject *leader = [organization valueForKey:#"leader"];
[self displayPerson:leader withIndentation:#" "];
}
}
- (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)applicationDidEnterBackground:(UIApplication *)application
{
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
- (void)applicationWillEnterForeground:(UIApplication *)application
{
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
- (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.
}
- (void)applicationWillTerminate:(UIApplication *)application
{
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
#end
These are the only codes that are important to the project. Yes, this is a very simple Core Data app.
There's a guide in the book to access the database by using sqlite3.
In Terminal.app:
Input: cd ~/Library/Application\ Support/iPhone\ Simulator
Input: find . -name "Core01.sqlite" –print
Output: ./6.0/Applications/25DB9FAD-6921-4791-9409-FF84F275D8A8/Documents/Core01.sqlite
Input: sqlite3 ./6.0/Applications/25DB9FAD-6921-4791-9409-FF84F275D8A8/Documents/Core01.sqlite
In sqlite3:
Input: sqlite> select Z_PK, ZID, ZLEADER, ZNAME from ZORGANIZATION;
Output: 1|-19904|2|Company, Inc.
Input: sqlite> select Z_PK, ZID, Z2EMPLOYEES, ZNAME from ZPERSON;
Output:
1|6050|2|Jane
2|-28989||John
3|28151|2|Bill
The problem is, the database is empty. Idk what went wrong, nor what I miss.
I think the problem is that you need to call the method -(void)saveContext after you set all the data in -(void)createData
Try this:
-(void)createData
{
NSManagedObject *organization = [NSEntityDescription insertNewObjectForEntityForName:#"Organization" inManagedObjectContext:self.managedObjectContext];
[organization setValue:#"Company, Inc." forKey:#"name"];
[organization setValue:[NSNumber numberWithInt:[#"Company, Inc." hash]] forKey:#"id"];
NSManagedObject *john = [NSEntityDescription insertNewObjectForEntityForName:#"Person" inManagedObjectContext:self.managedObjectContext];
[john setValue:#"John" forKey:#"name"];
[john setValue:[NSNumber numberWithInt:[#"John" hash]] forKey:#"id"];
NSManagedObject *jane = [NSEntityDescription insertNewObjectForEntityForName:#"Person" inManagedObjectContext:self.managedObjectContext];
[jane setValue:#"Jane" forKey:#"name"];
[jane setValue:[NSNumber numberWithInt:[#"Jane" hash]] forKey:#"id"];
NSManagedObject *bill = [NSEntityDescription insertNewObjectForEntityForName:#"Person" inManagedObjectContext:self.managedObjectContext];
[bill setValue:#"Bill" forKey:#"name"];
[bill setValue:[NSNumber numberWithInt:[#"Bill" hash]] forKey:#"id"];
NSMutableSet *johnsEmployees = [john mutableSetValueForKey:#"employees"];
[johnsEmployees addObject:jane];
[johnsEmployees addObject:bill];
[self saveContext];
}
Unless I missed it in the code, you call [self createData]; but never save the context.
At the end of your createData method, add in the [self saveContext]; call.

Completion block/callback on FetchRequest completion

I have a FetchRequest in my model class named ContentManager. It fetches quite a lot of data, so the screen is blank until it's completion. In the ViewController that displays the fetched results, I would like to show a loading indicator, so I would like to get a callback when the FetchRequest has completed and pass that to the ViewController to stop the loading indicator. Is this possible?
Here is the FetchRequest from the ContentManager class:
- (NSArray*)recipesForMagazine
{
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Recipe" inManagedObjectContext:managedObjectContext];
[request setEntity:entity];
NSString* path = [[NSBundle mainBundle] pathForResource:#"magazine_recipe_guids" ofType:#"plist"];
NSArray* recipeGuids = [NSArray arrayWithContentsOfFile:path];
NSPredicate* predicate = [NSPredicate predicateWithFormat:#"guid IN %#",recipeGuids];
[request setPredicate:predicate];
NSSortDescriptor* sort = [[NSSortDescriptor alloc] initWithKey:#"title" ascending:YES selector:#selector(localizedCaseInsensitiveCompare:)];
[request setSortDescriptors:[NSArray arrayWithObject:sort]];
[sort release];
NSError* error = nil;
NSArray* fetchResults = [managedObjectContext executeFetchRequest:request error:&error];
[request release];
return fetchResults;
}
Here I set it up in the ViewController
self.magazineRecipes = [[ContentManager defaultManager] recipesForMagazine];
I want to set up the fetchrequest method like this:
- (NSArray*)recipesForMagazine:(void (^)(BOOL success))block or something, so in the viewcontroller I can call it like this
self.magazineRecipes = [[CTContentManager defaultManager] recipesForMagazine:^(BOOL success) {
if (success) {
//stop activity indicator view
}
}];
I don't know if I'm at all in the right way of thinking, thanks for your help in advance!
I would make the viewController a delegate of the ContentManager class. So in the ContentManager.h I would do something like:
#protocol ContentManagerDelegate()
-(void) didFetchResults:(NSArray *) results;
-(void) didResultsFail: (NSError *) error;
#end
#interface ContentManager : <SuperClass Name>
-(id) initWithDelegate: (id<ContentManagerDelegate>) delegate;
#property (nonatomic, strong) id<ContentManagerDelegate> delegate;
#end
and in the implementation:
-(id) initWithDelegate: (id<ContentManagerDelegate>) delegate
{
self = [super init];
if(self)
{
_delegate = delegate;
}
return self;
}
and in your recipesForMagazine method you can use the delegate [_delegate didFetchResults: fetchResults], you can implement a method to pass errors to the delegate if you want as well. In your ViewController.h do #interface ViewController.h : UIViewController <ContentManagerDelegate> and in the implementation you should be able to implement the didFetchResults: method that will give you the results and in that method you can stop the activity indicator from animating.

Using core data in an existing project

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.

View in PersistenceCoreDataViewController.xib won't display

Yes, I'm a newbie, but I'd sure appreciate some help. I've got a fairly simple example app I'm working through in an effort to learn about Core Data. I've got a app that simply displays four text fields and allows a user to save text in those four fields.
The app compiles, but upon execution I get a "black" screen. I had initially assumed my problem was that my view in my PersitenecCoreDataViewController.xib wasn't displaying for some reason. However, in my debugger console I've found where my app is being terminated due to an uncaught exception:
NSInvalidArgumentException', reason:
'executeFetchRequest:error: A fetch
request must have an entity
I'm now thinking I'm not setting up my fetch request properly.
I've got my app delegate and viewController classes code listed below. Thanks in advance for your time and assistance. . .
// PersistenceCoreDataAppDelegate.h
// Created by RICHARD COLEMAN on 3/21/11.
#import <UIKit/UIKit.h>
#import <CoreData/CoreData.h>
#class PersistenceCoreDataViewController;
#interface PersistenceCoreDataAppDelegate : NSObject <UIApplicationDelegate> {
UIWindow* window;
PersistenceCoreDataViewController* rootController;
#private
NSManagedObjectContext* managedObjectContext_;
NSManagedObjectModel* managedObjectModel_;
NSPersistentStoreCoordinator* persistentStoreCoordinator_;
}
#property (nonatomic, retain) IBOutlet UIWindow* window;
#property (nonatomic, retain, readonly) NSManagedObjectContext* managedObjectContext;
#property (nonatomic, retain, readonly) NSManagedObjectModel* managedObjectModel;
#property (nonatomic, retain, readonly) NSPersistentStoreCoordinator* persistentStoreCoordinator;
#property (nonatomic, retain) IBOutlet PersistenceCoreDataViewController* rootController;
- (NSString *)applicationDocumentsDirectory;
#end
// PersistenceCoreDataAppDelegate.m
// Created by RICHARD COLEMAN on 3/21/11.
#import "PersistenceCoreDataAppDelegate.h"
#import "PersistenceCoreDataViewController.h"
#implementation PersistenceCoreDataAppDelegate
#synthesize window;
#synthesize rootController;
#pragma mark -
#pragma mark Application lifecycle
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
[window addSubview:rootController.view];
[window makeKeyAndVisible];
return YES;
}
// 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]) {
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
}
}
#pragma mark -
#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_;
}
NSString *modelPath = [[NSBundle mainBundle] pathForResource:#"PersistenceCoreData" ofType:#"momd"];
NSURL *modelURL = [NSURL fileURLWithPath:modelPath];
managedObjectModel_ = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return managedObjectModel_;
}
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
if (persistentStoreCoordinator_ != nil) {
return persistentStoreCoordinator_;
}
NSURL *storeURL = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory] stringByAppendingPathComponent: #"PersistenceCoreData.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 -
#pragma mark Applications Documents directory
- (NSString *)applicationDocumentsDirectory {
return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
}
#pragma mark -
#pragma mark Memory management
- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application {
}
- (void)dealloc {
[managedObjectContext_ release];
[managedObjectModel_ release];
[persistentStoreCoordinator_ release];
[window release];
[super dealloc];
}
#end
// PersistenceCoreDataViewController.h
// Created by RICHARD COLEMAN on 3/21/11.
#import <UIKit/UIKit.h>
#interface PersistenceCoreDataViewController : UIViewController {
UITextField* line1;
UITextField* line2;
UITextField* line3;
UITextField* line4;
}
#property (nonatomic, retain) IBOutlet UITextField* line1;
#property (nonatomic, retain) IBOutlet UITextField* line2;
#property (nonatomic, retain) IBOutlet UITextField* line3;
#property (nonatomic, retain) IBOutlet UITextField* line4;
#end
// PersistenceCoreDataViewController.m
// Created by RICHARD COLEMAN on 3/21/11.
#import "PersistenceCoreDataViewController.h"
#import "PersistenceCoreDataAppDelegate.h"
#implementation PersistenceCoreDataViewController
#synthesize line1;
#synthesize line2;
#synthesize line3;
#synthesize line4;
- (void)applicationWillTerminate:(NSNotification *)notification {
// Get a reference to our application delegate, which we then use to get the managed object context,
// i.e. context, that was created for us
// Remember an application delegate performs a specific action at a certain predefined time on behalf
// of the application
PersistenceCoreDataAppDelegate* appDelegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext* context = [appDelegate managedObjectContext];
NSError* error;
// Loop to execute 4x, ie. once for each line
for (int i = 1; i <= 4; i++) {
// Obtain field name by appending value of i to line
NSString* fieldName = [NSString stringWithFormat:#" line%d", i];
// Obtain reference to the correct field
UITextField* theField = [self valueForKey:fieldName];
// Create fetch request; remember a fetch request is just a predefined query
NSFetchRequest* request = [[NSFetchRequest alloc] init];
// Create entity description (describing Line entity using correct context we retrieved
// from application delegate) that will be fed to fetch request so it knows what type
// of entity to look for
NSEntityDescription* entityDescription = [NSEntityDescription entityForName:#" Line"
inManagedObjectContext:context];
[request setEntity:entityDescription];
// Create a predicate that identifies the right object for the field (this will help us
// find out if there is already a managed object in the persistent store that corresponds
// to this field
// managed object - instance of entity
// persistent store - area where managed objects exist
NSPredicate* pred = [NSPredicate predicateWithFormat:#"(lineNum = %d)", i];
[request setPredicate:pred];
// Declared pointer and set to nil b/c we don't know yet if we're going to load a managed object
// from the persistent store or create a new one
NSManagedObject* theLine = nil;
// Actually exec the fetch against the given context; rememeber the fetch request is just a query
// and the context is where we manage the state, access, info about properties, etc.
NSArray* objects = [context executeFetchRequest:request error:&error];
// Checking to see if objects are nil; if nil there was an error; handle appropriately
if (objects == nil) {
NSLog(#" There was an error!");
// Do whatever error handling is appropriate
}
// Was an object returned that matched our criteria; if there is one, load it; if not create one
if ([objects count] > 0)
theLine = [objects objectAtIndex:0];
else
theLine = [NSEntityDescription insertNewObjectForEntityForName:#" Line"
inManagedObjectContext:context];
// use key-value coding to set the line number and text for this managed object
[theLine setValue:[NSNumber numberWithInt:i] forKey:#" lineNum"];
[theLine setValue:theField.text forKey:#" lineText"];
[request release];
}
// looping is complete, save changes
[context save:&error];
}
// this method needs to determine if there is any existing data and if so, load it
- (void)viewDidLoad {
// get a reference to the application delegate and use it to get a pointer to the application's
// default context
PersistenceCoreDataAppDelegate* appDelegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext* context = [appDelegate managedObjectContext];
// Create an Entity Description that describes our entity
NSEntityDescription* entityDescription = [NSEntityDescription entityForName:#" Line"
inManagedObjectContext:context];
// Create a fetch request, i.e. a query, and pass it the entity description so it knows what type
// of objects to retriev
NSFetchRequest* request = [[NSFetchRequest alloc] init];
[request setEntity:entityDescription];
// We don't create a predicate as we want to retrieve all Line objects in the persistent store
NSError* error;
NSArray* objects = [context executeFetchRequest:request error:&error];
// Ensure we get back a valid array
if (objects == nil) {
NSLog(#" There was an error!");
// Do whatever error handling is appropriate
}
// Using fast enumeration to loop thru array of retrieved managed objects pulling out the lineNum
// and lineText and updating one of the text fields on our user interface
for (NSManagedObject* oneObject in objects) {
NSNumber* lineNum = [oneObject valueForKey:#" lineNum"];
NSString* lineText = [oneObject valueForKey:#" lineText"];
NSString* fieldName = [NSString stringWithFormat:#" line%#", lineNum];
UITextField* theField = [self valueForKey:fieldName];
theField.text = lineText;
}
[request release];
// Register to be notified when the app is about to terminate so you can save any changes the user
// has made to the data
UIApplication *app = [UIApplication sharedApplication];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(applicationWillTerminate:)
name:UIApplicationWillTerminateNotification
object:app];
[super viewDidLoad];
}
// Override to allow orientations other than the default portrait orientation.
-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
self.line1 = nil;
self.line2 = nil;
self.line3 = nil;
self.line4 = nil;
[super viewDidUnload];
}
- (void)dealloc {
[line1 release];
[line2 release];
[line3 release];
[line4 release];
[super dealloc];
}
#end
# Julien and fluchtpunkt.. I am pretty new too and I was wondering if there being a space there cause problems??
I may be wrong but seeing your error message " fetch request must have an entity" made me wonder if you did create the entity and the related attributes you want using core data? that is the first thing that comes to my mind.. let me know..

How to refresh a TableView when data is inserted in the AppDelegate?

To pre-populate my Database for a small Iphone-App I do a check in the persistentStoreCoordinator Method in the AppDelegate if the sqlite-file is already there or not. If not I add some data into a table after the db is created. But the data should not directly shown in the RootViewController but in another TableView which can be accessed by pressing a Option in the RootViewController.
The Problem is that the data are saved but are not shown in the TableView. But if terminate and restart the app the data are there.
I have passed the managedObjectContext from my appDelegate to the the RootViewController and from there to the TableViewController. So the managedObjectContext is the same everywhere.
Here is the Code where I pre-populate the DB (in this example just one sample row):
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
if (persistentStoreCoordinator_ != nil) {
return persistentStoreCoordinator_;
}
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:#"TestDBApp.sqlite"];
NSString *storePath = [storeURL relativePath];
BOOL noDb = false;
NSFileManager *fileManager = [NSFileManager defaultManager];
if( ![fileManager fileExistsAtPath:storePath]) {
noDb = true;
}
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();
}
if( noDb) {
noDb = false;
[self populateDB];
}
return persistentStoreCoordinator_;
}
- (void) populateDB {
// Create the fetch request for the entity.
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
// Edit the entity name as appropriate.
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Kunde" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
// Edit the sort key as appropriate.
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"oxid" ascending:NO];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[fetchRequest setSortDescriptors:sortDescriptors];
NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:#"Root"];
NSError *error = nil;
if (![aFetchedResultsController performFetch:&error]) {
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
[self insertNewKunde:aFetchedResultsController];
[self saveContext];
[aFetchedResultsController release];
[sortDescriptors release];
[sortDescriptor release];
[fetchRequest release];
}
- (void)insertNewKunde:(NSFetchedResultsController *)fetchedResultsController {
// Create a new instance of the entity managed by the fetched results controller.
NSManagedObjectContext *context = [fetchedResultsController managedObjectContext];
NSEntityDescription *entity = [[fetchedResultsController fetchRequest] entity];
NSManagedObject *newManagedObject = [NSEntityDescription insertNewObjectForEntityForName:[entity name] inManagedObjectContext:context];
// If appropriate, configure the new managed object.
[newManagedObject setValue:[[NSDate date] description] forKey:#"oxid"];
[newManagedObject setValue:#"Max" forKey:#"fname"];
[newManagedObject setValue:#"Mustermann" forKey:#"lname"];
// Save the context.
NSError *error = nil;
if (![context save:&error]) {
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
}
The managedObjectContext is passed from the AppDelegate to the RootViewController as:
- (void)awakeFromNib {
RootViewController *rootViewController = (RootViewController *)[navigationController topViewController];
rootViewController.managedObjectContext = self.managedObjectContext;
}
and to the other TableViewController:
- (void)awakeFromNib {
kundenVC = [[KundenViewController alloc] initWithManagedObjectContext:self.managedObjectContext];
}
Can anyone help me or give a hint?
I also tried to reload the tableView through the viewWillAppear-Method. But no effect.
It is very difficult to guess what is happening but my hunch is that you are not calling self.populateDB until the RootViewController is actually created. This means the RootViewController does not see that data because it is not created.
I could be wrong but I guess that your last line in delegate's awakeFromNib method is eventually calling populateDB through self.managedObjectContext -> persistentStoreCoordinator -> self.populateDB.
Please try to add a line right at the top of awakeFromNib looking like this:
(void)awakeFromNib {
NSManagedObjectContext *context = self.managedObjectContext;
RootViewController *rootViewController = (RootViewController *)[navigationController topViewController];
rootViewController.managedObjectContext = context;}
This way I hope the your problem is solved because self.managedObjectContext will call the getter (- (NSManagedObjectContext)managedObjectContext;) instead of the field. Inside there (if you use the generated code) there is a call to the getter of ** persistentStoreCoordinator** which eventually calls you populateDB method.
In case that does not work go ahead and set a breakpoint inside your populateDB. When the debugger stops you should see at the method call stack where you populateDB is actually called from and that might help to figure out your problem.
-Andy
Well, the important part you left out to answer your question. What is [self saveContext] and how are you displaying the records in your table view.
Because your data is saved I assume that the code given here works. The only guess I can make is to use reset on the NSManagedObjectContext and then refetch.
BTW I like the "insertNewKunde" which seems to be the new German grammar ;-)