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.
Related
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.
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.
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..
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".
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! ;)