Error in iPhone core data - iphone

My AppDelegate.h:
#import <UIKit/UIKit.h>
#import "Child.h"
#interface AppDelegate : UIResponder <UIApplicationDelegate> {
NSManagedObjectModel *managedObjectModel;
NSManagedObjectContext *managedObjectContext;
NSPersistentStoreCoordinator *persistentStoreCoordinator;
}
#property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
#property (readonly, retain, nonatomic) NSManagedObjectModel *managedObjectModel;
#property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;
- (NSString *)applicationDocumentsDirectory;
#property (strong, nonatomic) UIWindow *window;
#end
AppDelegate.m:
#import "AppDelegate.h"
#implementation AppDelegate
#synthesize managedObjectContext = __managedObjectContext;
#synthesize managedObjectModel = __managedObjectModel;
#synthesize persistentStoreCoordinator = __persistentStoreCoordinator;
#synthesize window = _window;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
NSManagedObjectContext *context = [self managedObjectContext];
if (!context) {
NSLog(#"Error");
}
return YES;
}
- (void)applicationWillTerminate:(UIApplication *)application { /* Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. */
NSError *error;
if (managedObjectContext != nil) {
if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
// Handle the error.
}
}
}
// Explicitly write Core Data accessors
- (NSManagedObjectContext *) managedObjectContext {
if (managedObjectContext != nil) {
return managedObjectContext;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil) {
managedObjectContext = [[NSManagedObjectContext alloc] init];
[managedObjectContext setPersistentStoreCoordinator: coordinator];
}
return managedObjectContext;
}
- (NSManagedObjectModel *)managedObjectModel {
if (managedObjectModel != nil) {
return managedObjectModel;
}
managedObjectModel = [NSManagedObjectModel mergedModelFromBundles:nil];
return managedObjectModel;
}
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
if (persistentStoreCoordinator != nil) {
return persistentStoreCoordinator;
}
NSURL *storeUrl = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory] stringByAppendingPathComponent: #"iSalahProject.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 {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
return basePath;
}
#end
My controller implementation class where entity is being created and I am getting the error:
-(IBAction)addChildren:(id)sender{
inputChildName = nameOfChild.text;
NSManagedObjectContext *context = [app managedObjectContext];
Child * childrenName = [NSEntityDescription insertNewObjectForEntityForName:#"Child" inManagedObjectContext:context];
childrenName.name = inputChildName;
}
The error I am getting is:
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '+entityForName: could not locate an NSManagedObjectModel for entity name 'Child''
I am using iOS-5 XCode 4.2 ARC. Please help me resolving this issue, I already have spent hours resolving it, but I couldn't find any solutions.

Your application is terminating because your managedObjectContext is nil. Check for it and if its nil copy it from delegate. You can use this if condition in your -(IBAction)addChildren:(id)sender method
if (managedObjectContext == nil)
{
managedObjectContext = [(CoreDataBooksAppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
NSLog(#"After managedObjectContext: %#", managedObjectContext);
}

Following are the possibilities for this error to occur:
Typo in the Entity name.
Nil managed object context object.
Failure to add the model containing the entity to the persistent
store the context uses.
Failure to add the correct persistent store to the context itself.

Related

Issue CoreData Migration

I have an App with two sqlite databases and two xcdatamodel´s. So every things fine, except if i want to change or add some properties to one of the models.
I am creating a new model version and make my changes to that. After Setting the current model version, i start my app and get following Exception:
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'This NSPersistentStoreCoordinator has no persistent stores. It cannot perform a save operation.'
I have the following Manager for my CoreData Operations:
#interface CoreDataManager ()
#property (strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;
#property (strong, nonatomic) NSManagedObjectModel *managedObjectModel;
#property (strong, nonatomic) NSManagedObjectContext *mainQueueContext;
#property (strong, nonatomic) NSManagedObjectContext *privateQueueContext;
#end
#implementation CoreDataManager
+ (instancetype)defaultStore
{
static CoreDataManager *_defaultStore = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_defaultStore = [self new];
});
return _defaultStore;
}
#pragma mark - Singleton Access
+ (NSManagedObjectContext *)mainQueueContextWithDB:(NSString *)db
{
return [[self defaultStore] mainQueueContextWithDB:db];
}
+ (NSManagedObjectContext *)privateQueueContextWithDB:(NSString *)db
{
return [[self defaultStore] privateQueueContextWithDB:db];
}
+ (NSManagedObjectID *)managedObjectIDFromString:(NSString *)managedObjectIDString
{
return [[[self defaultStore] persistentStoreCoordinator] managedObjectIDForURIRepresentation:[NSURL URLWithString:managedObjectIDString]];
}
#pragma mark - Lifecycle
- (id)init
{
self = [super init];
if (self) {
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(contextDidSavePrivateQueueContext:)name:NSManagedObjectContextDidSaveNotification object:[self privateQueueContext]];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(contextDidSaveMainQueueContext:) name:NSManagedObjectContextDidSaveNotification object:[self mainQueueContext]];
}
return self;
}
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
#pragma mark - Notifications
- (void)contextDidSavePrivateQueueContext:(NSNotification *)notification
{
#synchronized(self) {
[self.mainQueueContext performBlock:^{
[self.mainQueueContext mergeChangesFromContextDidSaveNotification:notification];
}];
}
}
- (void)contextDidSaveMainQueueContext:(NSNotification *)notification
{
#synchronized(self) {
[self.privateQueueContext performBlock:^{
[self.privateQueueContext mergeChangesFromContextDidSaveNotification:notification];
}];
}
}
#pragma mark - Getters
- (NSManagedObjectContext *)mainQueueContextWithDB:(NSString *)db
{
actualDB = db;
if (!_mainQueueContext) {
_mainQueueContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
_mainQueueContext.persistentStoreCoordinator = self.persistentStoreCoordinator;
}
return _mainQueueContext;
}
- (NSManagedObjectContext *)privateQueueContextWithDB:(NSString *)db
{
actualDB = db;
if (!_privateQueueContext) {
_privateQueueContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
_privateQueueContext.persistentStoreCoordinator = self.persistentStoreCoordinator;
}
return _privateQueueContext;
}
#pragma mark - Stack Setup
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
if (!_persistentStoreCoordinator) {
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:self.managedObjectModel];
NSError *error = nil;
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[self persistentStoreURL] options:[self persistentStoreOptions] error:&error]) {
NSLog(#"Error adding persistent store. %#, %#", error, error.userInfo);
}
}
return _persistentStoreCoordinator;
}
- (NSManagedObjectModel *)managedObjectModel
{
if (_managedObjectModel != nil) {
return _managedObjectModel;
}
_managedObjectModel = [NSManagedObjectModel mergedModelFromBundles:nil];
return _managedObjectModel;
}
- (NSURL *)persistentStoreURL
{
return [[NSFileManager appLibraryDirectory] URLByAppendingPathComponent:actualDB];
}
- (NSDictionary *)persistentStoreOptions
{
return #{NSInferMappingModelAutomaticallyOption: #YES, NSMigratePersistentStoresAutomaticallyOption: #YES};
}
#end
You may try to change the journal_mode to DELETE (guess WAL is default in Core Data on iOS 7 and higher ?!?). The persistent store options which i use and having no trouble with dozens of data model changes is:
NSMutableDictionary *options = [NSMutableDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
[NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption,
#{#"journal_mode" : #"DELETE"}, NSSQLitePragmasOption, nil];
I hope it helps ...
About Journal Mode on http://www.sqlite.org/pragma.html:
"The DELETE journaling mode is the normal behavior. In the DELETE mode, the rollback journal is deleted at the conclusion of each transaction. Indeed, the delete operation is the action that causes the transaction to commit. (See the document titled Atomic Commit In SQLite for additional detail.)"

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.

Starting Xcode Project From Scratch and cannot showing anything

I am following a book (Big Nerd Ranch IOS Programming) and the version of my xcode that I am using is slightly newer than the one that the book uses. As a consequence, I cannot exactly follow the books steps and one of those steps is to create a window-based application.
What I did was: I created an empty project which gives me the delegate and a few other files. I created my own MainWindow.xib.
I kept on reading and I am at the part where I need to compile and I am supposed to see something on the simulator. However, I do not see anything. I know that I am missing something here, because I am guessing that I have not wired up the MainWindow.xib correctly with the code (??). Note that the book told me to add map view, text field, and activity indicator to the main window.
I am wondering what is the proper way to get a project started from scratch. I actually prefer doing it this way so that I can get the lowdown of starting a ios project.
UPDATE:
After I set the Info.plist "Main nib file base name" to "MainWindow". I was able to see the view. However, I cannot click on the text field on the simulator and make the keyboard show up. I clicked the home button and when I tried clicking on the icon again, It would show white screen and not the map with text field over it.
WhereamiAppDelegate.h
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
#import <MapKit/MapKit.h>
#interface WhereamiAppDelegate : UIResponder <UIApplicationDelegate, CLLocationManagerDelegate>{
CLLocationManager * locationManager;
IBOutlet MKMapView *worldView;
IBOutlet UIActivityIndicatorView *activityIndicator;
IBOutlet UITextField *locationTitleField;
}
#property (strong, nonatomic) IBOutlet UIWindow *window;
#property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
#property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
#property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;
- (void)saveContext;
- (NSURL *)applicationDocumentsDirectory;
#end
WhereamiAppDelegate.m
#import "WhereamiAppDelegate.h"
#implementation WhereamiAppDelegate
#synthesize window = _window;
#synthesize managedObjectContext = __managedObjectContext;
#synthesize managedObjectModel = __managedObjectModel;
#synthesize persistentStoreCoordinator = __persistentStoreCoordinator;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
locationManager = [[CLLocationManager alloc] init];
[locationManager setDelegate:self];
[locationManager setDistanceFilter:kCLDistanceFilterNone];
[locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
[locationManager startUpdatingLocation];
[worldView setShowsUserLocation:YES];
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}
- (void) locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{
NSLog(#"%#", newLocation);
}
- (void) locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
NSLog(#"Could not find location: %#", error);
}
- (void)applicationWillResignActive:(UIApplication *)application
{
}
- (void)applicationDidEnterBackground:(UIApplication *)application
{
}
- (void)applicationWillEnterForeground:(UIApplication *)application
{
/*
Called as part of the transition from the background to the active 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
{
// Saves changes in the application's managed object context before the application terminates.
[self saveContext];
}
- (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:#"whereami" withExtension:#"momd"];
__managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return __managedObjectModel;
}
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
if (__persistentStoreCoordinator != nil)
{
return __persistentStoreCoordinator;
}
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:#"whereami.sqlite"];
NSError *error = nil;
__persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
if (![__persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error])
{
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
return __persistentStoreCoordinator;
}
#pragma mark - Application's Documents directory
- (NSURL *)applicationDocumentsDirectory
{
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
#end
main.m
#import <UIKit/UIKit.h>
#import "WhereamiAppDelegate.h"
int main(int argc, char *argv[])
{
#autoreleasepool {
return UIApplicationMain(argc, argv, nil, NSStringFromClass([WhereamiAppDelegate class]));
}
}
See here (quoted from #WrightCS):
MainWindow.xib is the defined in your info.plist as the Main nib file
base name. In your MainWindow.xib, you define the first controller
that you want to load, in your case, RootViewController.
Check your main.m file (assuming you have one - if not, that's part of your problem). You'll probably see a line like this:
int retVal = UIApplicationMain(argc, argv, nil, nil);
For your app to do anything, it should be something like this:
int retVal = UIApplicationMain(argc, argv, #"UIApplication", #"MyAppDelegate");
Assuming you have MyAppDelegate.h and MyAppDelegate.m in your project.

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

[UIView didCreateWorkout:Type:Distance:Time:Message:]: unrecognized selector sent to instance

I'm getting the above error and have been looking at it all day, I'm getting no where fast. Anyone any ideas ? I'm new to IPhone Development. Code Below:
WorkoutAppDelegate.h...:
#import "WorkoutViewController.h"
#interface WorkoutAppDelegate : NSObject <UIApplicationDelegate> {
NSManagedObjectModel *managedObjectModel;
NSManagedObjectContext *managedObjectContext;
NSPersistentStoreCoordinator *persistentStoreCoordinator;
UIWindow *window;
WorkoutViewController *viewController;
}
- (IBAction)saveAction:sender;
#property (nonatomic, retain, readonly) NSManagedObjectModel *managedObjectModel;
#property (nonatomic, retain, readonly) NSManagedObjectContext *managedObjectContext;
#property (nonatomic, retain, readonly) NSPersistentStoreCoordinator *persistentStoreCoordinator;
#property (nonatomic, readonly) NSString *applicationDocumentsDirectory;
#property (nonatomic, retain) IBOutlet UIWindow *window;
#property (nonatomic, retain) IBOutlet WorkoutViewController *viewController;
#end
WorkoutAppDelegate.m....:
#import "WorkoutAppDelegate.h"
#implementation WorkoutAppDelegate
#synthesize window;
#synthesize viewController;
- (void)applicationDidFinishLaunching:(UIApplication *)application {
// Override point for customization after app launch
viewController.managedObjectContext = [self managedObjectContext];
[window addSubview:viewController.view];
[window makeKeyAndVisible];
}
/**
applicationWillTerminate: saves changes in the application's managed object context before the application terminates.
*/
- (void)applicationWillTerminate:(UIApplication *)application {
NSError *error;
if (managedObjectContext != nil) {
if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
// Handle error
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort(); // Fail
}
}
}
/**
Performs the save action for the application, which is to send the save:
message to the application's managed object context.
*/
- (IBAction)saveAction:(id)sender {
NSError *error;
if (![[self managedObjectContext] save:&error]) {
// Handle error
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort(); // Fail
}
}
/**
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 by merging all of the models found in the application bundle.
*/
- (NSManagedObjectModel *)managedObjectModel {
if (managedObjectModel != nil) {
return managedObjectModel;
}
managedObjectModel = [[NSManagedObjectModel mergedModelFromBundles:nil] retain];
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: #"WorkoutCoreData.sqlite"]];
NSError *error;
persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel: [self managedObjectModel]];
if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:nil error:&error]) {
// Handle error
}
return persistentStoreCoordinator;
}
/**
Returns the path to the application's documents directory.
*/
- (NSString *)applicationDocumentsDirectory {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
return basePath;
}
- (void)dealloc {
[managedObjectContext release];
[managedObjectModel release];
[persistentStoreCoordinator release];
[viewController release];
[window release];
[super dealloc];
}
#end
WorkoutViewController.h...:
#import <UIKit/UIKit.h>
#import "Workout.h"
#protocol CreateWorkoutDelegate <NSObject>
-(void)didCancelWorkout;
-(void)didCreateWorkout:(NSString *)thisRoute
Type:(NSString *)thisType
Distance:(NSString *)thisDistance
Time:(NSString *)thisTime
Message:(NSString *)thisMessage;
#end
#interface WorkoutViewController : UIViewController {
// IBOutlet UIlabel *Speed;
// IBOutlet UIlabel *Calories;
IBOutlet UILabel *DBContents;
IBOutlet UITextField *route;
IBOutlet UITextField *type;
IBOutlet UITextField *distance;
IBOutlet UITextField *time;
IBOutlet UITextField *message;
IBOutlet UIButton *saveWorkout;
IBOutlet UIButton *cancelWorkout;
NSMutableArray *workoutArray;
id workoutDelegate;
Workout *currentWorkout;
NSManagedObjectContext *managedObjectContext;
}
//#property (retain,nonatomic) UILabel *Speed;
//#property (retain,nonatomic) UILabel *Calories;
#property (retain,nonatomic) UILabel *DBContents;
#property (retain,nonatomic) UITextField *route;
#property (retain,nonatomic) UITextField *type;
#property (retain,nonatomic) UITextField *distance;
#property (retain,nonatomic) UITextField *time;
#property (retain,nonatomic) UITextField *message;
#property (retain,nonatomic) NSMutableArray *workoutArray;
//#property (retain,nonatomic) UIButton *saveWorkout;
//#property (retain,nonatomic) UIButton *cancelWorkout;
#property (nonatomic, assign) id<CreateWorkoutDelegate> workoutDelegate;
#property (nonatomic, assign) NSManagedObjectContext *managedObjectContext;
-(IBAction)hideKeyboard;
-(IBAction)saveWorkout;
-(IBAction)cancelWorkout;
#end
WorkoutViewController.m...:
#import "WorkoutViewController.h"
#import "Workout.h"
#implementation WorkoutViewController
#synthesize workoutDelegate;
//#synthesize Speed;
//#synthesize Calories;
#synthesize route;
#synthesize type;
#synthesize distance;
#synthesize time;
#synthesize message;
#synthesize DBContents;
#synthesize workoutArray;
#synthesize managedObjectContext;
//#synthesize saveWorkout;
//#synthesize cancelWorkout;
-(IBAction)hideKeyboard {
}
-(IBAction)saveWorkout {
[workoutDelegate didCreateWorkout: route.text
Type: type.text
Distance: distance.text
Time: time.text
Message: message.text];
}
-(IBAction)cancelWorkout {
[self.workoutDelegate didCancelWorkout];
}
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
-(void)viewDidLoad {
//Set images for Save & Cancel buttons.
UIImage *normalImage = [[UIImage imageNamed:#"whiteButton.png"]
stretchableImageWithLeftCapWidth:12.0
topCapHeight:0.0];
[saveWorkout setBackgroundImage:normalImage forState:UIControlStateNormal];
[cancelWorkout setBackgroundImage:normalImage forState:UIControlStateNormal];
UIImage *pressedImage = [[UIImage imageNamed:#"blueButton.png"]
stretchableImageWithLeftCapWidth:12.0
topCapHeight:0.0];
[saveWorkout setBackgroundImage:pressedImage forState:UIControlStateHighlighted];
[cancelWorkout setBackgroundImage:pressedImage forState:UIControlStateHighlighted];
//Fetch details from the database.
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Workout" inManagedObjectContext:managedObjectContext];
[request setEntity:entity];
NSError *error;
self.workoutArray = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
[request release];
//self.workoutArray = [[NSMutableArray alloc] init];
//self.DBContents.text = [self.workoutArray objectAtIndex:0];
[super viewDidLoad];
}
-(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;
}
-(void) didCreateWorkout:(NSString *)thisRoute
Type:(NSString *)thisType
Distance:(NSString *)thisDistance
Time:(NSString *)thisTime
Message:(NSString *)thisMessage {
// Add the new workout.
Workout *newWorkout = [NSEntityDescription
insertNewObjectForEntityForName:#"Workout"
inManagedObjectContext:self.managedObjectContext];
newWorkout.route = thisRoute;
newWorkout.type = thisType;
newWorkout.distance = thisDistance;
newWorkout.time = thisTime;
newWorkout.message = thisMessage;
[self.workoutArray addObject:newWorkout];
//[self dismissModalViewControllerAnimated:YES];
}
-(void)didCancelWorkout {
[self dismissModalViewControllerAnimated:YES];
}
-(void)dealloc {
// [Speed release];
// [Calories release];
[route release];
[type release];
[distance release];
[time release];
[message release];
// [saveWorkout release];
// [cancelWorkout release];
[workoutArray release];
[managedObjectContext release];
[super dealloc];
}
#end
I'm trying to save details that I key on the screen (WorkoutViewController.xib) and I click the save button and get the above error.
Thanks
Stephen
The error is saying that UiView does not know (does not implement) the method -(void)didCreateWorkout .......and really if you look where you have implemented this method, you will see it is in WorkoutViewController (WorkoutViewController.m), which is not an UIView (I presume you have only one implementation of didCreateWorkout in your project). You should double check how you set the workoutDelegate property. From the code you show us it should be an instance of WorkoutViewController.
Btw., because you are having the implementaion of the -(IBAction)saveWorkout also in WorkoutViewController the quick fix for this particular problem would be to change the code of your actions to:
-(IBAction)saveWorkout {
[self didCreateWorkout: route.text
Type: type.text
Distance: distance.text
Time: time.text
Message: message.text];
}
-(IBAction)cancelWorkout {
[self didCancelWorkout];
}
However, this quick fix will not fix the problem with the design you probably intended. You should think through who should implement CreateWorkoutDelegate and then properly set the workoutDelegate property.
On a different topic I noticed two things in your code, which you might to consider to change:
use self.property=nil instead of [ivar release] in your dealloc methods
NSString properties should have attribute copy (in order to protect yourself from NSMutableString instances)
Good luck! ;)