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.
Related
I have a FetchRequest in my model class named ContentManager. It fetches quite a lot of data, so the screen is blank until it's completion. In the ViewController that displays the fetched results, I would like to show a loading indicator, so I would like to get a callback when the FetchRequest has completed and pass that to the ViewController to stop the loading indicator. Is this possible?
Here is the FetchRequest from the ContentManager class:
- (NSArray*)recipesForMagazine
{
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Recipe" inManagedObjectContext:managedObjectContext];
[request setEntity:entity];
NSString* path = [[NSBundle mainBundle] pathForResource:#"magazine_recipe_guids" ofType:#"plist"];
NSArray* recipeGuids = [NSArray arrayWithContentsOfFile:path];
NSPredicate* predicate = [NSPredicate predicateWithFormat:#"guid IN %#",recipeGuids];
[request setPredicate:predicate];
NSSortDescriptor* sort = [[NSSortDescriptor alloc] initWithKey:#"title" ascending:YES selector:#selector(localizedCaseInsensitiveCompare:)];
[request setSortDescriptors:[NSArray arrayWithObject:sort]];
[sort release];
NSError* error = nil;
NSArray* fetchResults = [managedObjectContext executeFetchRequest:request error:&error];
[request release];
return fetchResults;
}
Here I set it up in the ViewController
self.magazineRecipes = [[ContentManager defaultManager] recipesForMagazine];
I want to set up the fetchrequest method like this:
- (NSArray*)recipesForMagazine:(void (^)(BOOL success))block or something, so in the viewcontroller I can call it like this
self.magazineRecipes = [[CTContentManager defaultManager] recipesForMagazine:^(BOOL success) {
if (success) {
//stop activity indicator view
}
}];
I don't know if I'm at all in the right way of thinking, thanks for your help in advance!
I would make the viewController a delegate of the ContentManager class. So in the ContentManager.h I would do something like:
#protocol ContentManagerDelegate()
-(void) didFetchResults:(NSArray *) results;
-(void) didResultsFail: (NSError *) error;
#end
#interface ContentManager : <SuperClass Name>
-(id) initWithDelegate: (id<ContentManagerDelegate>) delegate;
#property (nonatomic, strong) id<ContentManagerDelegate> delegate;
#end
and in the implementation:
-(id) initWithDelegate: (id<ContentManagerDelegate>) delegate
{
self = [super init];
if(self)
{
_delegate = delegate;
}
return self;
}
and in your recipesForMagazine method you can use the delegate [_delegate didFetchResults: fetchResults], you can implement a method to pass errors to the delegate if you want as well. In your ViewController.h do #interface ViewController.h : UIViewController <ContentManagerDelegate> and in the implementation you should be able to implement the didFetchResults: method that will give you the results and in that method you can stop the activity indicator from animating.
I am trying to test this program on use of Core data. Once again, this is an example from the Dave Marks book. It has four text fields on a view and it loads it by using core data to connect to the database.
The app was created as a window based application and then I added a viewController to it. The file's owner is a sub class of the custom viewController class that I have created.
When I execute it, the UIView comes up with a blank view with no text boxes or labels that I had created in the view.
I put a break point in the main method, it does not even go anywhere from there when I click on step into method button. When I place a break point on the viewDidLoad method, it does not even get to it.
Lastly I do not get any errors on the console. What is going on?
Here is the viewController class:
#import "PersistenceViewController.h"
#import "CoreDataPersistenceAppDelegate.h"
#implementation PersistenceViewController
#synthesize line1;
#synthesize line2;
#synthesize line3;
#synthesize line4;
#pragma mark - View lifecycle
- (void)viewDidLoad
{
CoreDataPersistenceAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:#"Line" inManagedObjectContext:context];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entityDescription];
NSError *error;
NSArray *objects = [context executeFetchRequest:request error:&error];
if (objects == nil) {
NSLog(#"There was an error");
}
for (NSManagedObject *oneObject in objects) {
NSNumber *lineNum = [oneObject valueForKey:#"lineNum"];
NSString *lineText = [oneObject valueForKey:#"lineText"];
NSString *fieldName = [NSString stringWithFormat:#"line%d", [lineNum integerValue]];
UITextField *theField = [self valueForKey:fieldName];
theField.text = lineText;
}
[request release];
UIApplication *app = [UIApplication sharedApplication];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(applicationWillResignActive:) name:UIApplicationWillResignActiveNotification object:app];
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
-(void) applicationWillResignActive:(NSNotification *)notification {
CoreDataPersistenceAppDelegate *appDelegate = [[UIApplication sharedApplication]delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSError *error;
for (int i=1; i<=4; i++) {
NSString *fieldName = [NSString stringWithFormat:#"line%d",i];
UITextField *theField = [self valueForKey:fieldName];
NSFetchRequest *request = [[NSFetchRequest alloc]init];
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:#"Line" inManagedObjectContext:context];
[request setEntity:entityDescription];
NSPredicate *pred = [NSPredicate predicateWithFormat:#"(lineNum = %d)", i];
[request setPredicate:pred];
NSManagedObject *theLine = nil;
NSArray *objects = [context executeFetchRequest:request error:&error];
if (objects == nil) {
NSLog(#"There was an error");
}
if ([objects count] > 0)
theLine = [objects objectAtIndex:0];
else
theLine = [NSEntityDescription insertNewObjectForEntityForName:#"Line" inManagedObjectContext:context];
[theLine setValue:[NSNumber numberWithInt:i] forKey:#"lineNum"];
[theLine setValue:theField.text forKey:#"lineText"];
[request release];
}
[context save:&error];
}
- (void)viewDidUnload
{
self.line1 = nil;
self.line2 = nil;
self.line3 = nil;
self.line4 = nil;
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc
{
[line1 release];
[line2 release];
[line1 release];
[line1 release];
[super dealloc];
}
- (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.
}
#end
Be sure to change the viewcontroller that gets intialized in the appdelegate with the correct nib. The blank UIView is probably the view created when you started the project.
In your AppDelegate there is a method called applicationdidFinishLaunchingWithOptions, in which something like the following code is located:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.
self.viewController = [[RIViewController alloc] initWithNibName:#"RIViewController" bundle:nil];
self.window.rootViewController = self.viewController;
[self.window makeKeyAndVisible];
return YES;
}
In my case I load the RIViewController. By default the nib file has the same name as the controller and is hence named RIViewController aswell.
I have a huge problem with NSFetchedResultsCOntroller. I'm using fetchedResultsContrioller and I have interface with 3 tabs. They use Core Data too. But I have a problem with only ONE of them.
Faktura *faktura = [self.fetchedResultsController objectAtIndexPath:indexPath];
cell.textLabel.text = faktura.NumerFV; // THE CRASH IS HERE
int productsCount = [faktura.Produkty count]; // OR HERE
NSString *kontrahentName = [faktura.Kontrahent valueForKey:#"NazwaKrotka"]; // OR HERE
cell.detailTextLabel.text = [NSString stringWithFormat:#"nabywca: %#, produktów: %d",kontrahentName, productsCount];
cell.imageView.image = [UIImage imageNamed:#"faktura_cell_image.png"];
cell.hidesImageWhileEditing = YES;
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
Faktura is my NSManagedObject subclass.
NSZombie says:
-[CFDictionary retain]: message sent to deallocated instance 0x5d619d0
My fetchedResultsController implementation:
- (NSFetchedResultsController *)fetchedResultsController {
if (__fetchedResultsController != nil) return __fetchedResultsController;
// Setup the table
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Faktura" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
// Setup the sort descriptors
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"DataWystawienia" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[fetchRequest setSortDescriptors:sortDescriptors];
// Create the fetched results controller
NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:nil];
aFetchedResultsController.delegate = self;
self.fetchedResultsController = aFetchedResultsController;
[aFetchedResultsController release];
[fetchRequest release];
[sortDescriptor release];
[sortDescriptors release];
NSError *error = nil;
if (![self.fetchedResultsController performFetch:&error]) { // THE CRASH IS HERE UNLESS I INIT NSFetchedResultsController WITH cacheName:nil. (IF IT'LL BE cacheName:#"Root" IT CRASHES.)
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Błąd Krytyczny" message:#"Wystąpił nieznany błąd przy zmienianiu zawartości w bazie danych. Dla dobra twoich danych prosimy niezwłocznie wyjść z aplikacji i spróbować ponownie." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
return __fetchedResultsController;
}
Faktura.h
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
#interface NSArrayToDataTransformer : NSValueTransformer #end
#interface NSDictionaryToDataTransformer : NSValueTransformer #end
#interface Faktura : NSManagedObject
#property (nonatomic, retain) NSDate * DataZaplaty;
#property (nonatomic, retain) NSString * NumerFV;
#property (nonatomic, retain) NSDate * DataWystawienia;
#property (nonatomic, retain) NSDate * DataSprzedazy;
#property (nonatomic, retain) id Produkty;
#property (nonatomic, retain) id Kontrahent;
#end
Faktura.m
#import "Faktura.h"
#implementation Faktura
#dynamic DataZaplaty;
#dynamic NumerFV;
#dynamic DataWystawienia;
#dynamic DataSprzedazy;
#dynamic Produkty;
#dynamic Kontrahent;
+ (void)initialize {
if (self == [Faktura class] ) {
NSArrayToDataTransformer *arrayTransformer = [[NSArrayToDataTransformer alloc] init];
[NSValueTransformer setValueTransformer:arrayTransformer forName:#"NSArrayToDataTransformer"];
NSDictionaryToDataTransformer *dictTransformer = [[NSDictionaryToDataTransformer alloc] init];
[NSValueTransformer setValueTransformer:dictTransformer forName:#"NSDictionaryToDataTransformer"];
}
}
#end
#implementation NSArrayToDataTransformer
+ (BOOL)allowsReverseTransformation {
return YES;
}
+ (Class)transformedValueClass {
return [NSData class];
}
- (id)transformedValue:(id)value {
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:value];
return data;
}
- (id)reverseTransformedValue:(id)value {
NSArray *array = [NSKeyedUnarchiver unarchiveObjectWithData:value];
return [array autorelease];
}
#end
#implementation NSDictionaryToDataTransformer
+ (BOOL)allowsReverseTransformation {
return YES;
}
+ (Class)transformedValueClass {
return [NSData class];
}
- (id)transformedValue:(id)value {
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:value];
return data;
}
- (id)reverseTransformedValue:(id)value {
NSDictionary *dict = [NSKeyedUnarchiver unarchiveObjectWithData:value];
return [dict autorelease];
}
#end
My Faktura object insertion code
- (void)fakturaCreator:(FakturaCreator *)form didEndWithValues:(NSDictionary *)values {
NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];
NSEntityDescription *entity = [[self.fetchedResultsController fetchRequest] entity];
Faktura *newFaktura = [NSEntityDescription insertNewObjectForEntityForName:[entity name] inManagedObjectContext:context];
[newFaktura setNumerFV:[values valueForKey:#"id"]];
[newFaktura setDataWystawienia:[values valueForKey:#"creationDate"]];
[newFaktura setDataSprzedazy:[values valueForKey:#"sellDate"]];
[newFaktura setDataZaplaty:[values valueForKey:#"paymentDate"]];
[newFaktura setKontrahent:[values valueForKey:#"kontrahent"]];
[newFaktura setProdukty:[values valueForKey:#"produkty"]];
NSError *error = nil;
if (![context save:&error]) {
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
[self.emptySectionView setHidden:YES];
}
FakturaCreator is my UIViewController where user create an invoice. values array contains dictionary of values: my invoice number (NSString), various dates (NSDate), client (NSDictionary) and products (NSArray).
Please help me!
If you want some additional code, i'll put it here.
EDIT: It is definetly objectAtIndexPath: fault. When I comment all the cell setup code (it will display empty cell) and then try to remove the cell, app crashes on line which contains objectatIndexPath:.
EDIT #2: Anybody? Please, help me... :(
I think I see the problem. In your NSArrayToDataTransformer, you have this:
- (id)reverseTransformedValue:(id)value {
NSArray *array = [NSKeyedUnarchiver unarchiveObjectWithData:value];
return [array autorelease];
}
Since unarchiveObjectWithData: does not begin with "alloc", "new", "copy", or "mutableCopy", you do not own the object and therefore may not autorelease it. You have the same problem in your NSDictionaryToDataTransformer.
Your inclusion of the value transformers into the class and the using +initialize is non-standard. Although +initialize should work, it is recommended in the Core Data docs not use any kind of initialization methods at all but to rely on awakeFromFetch for initialization.
I would check your tableview methods such as numberOfRowsInSection: to ensure you are getting the right indexes back from the tableview. If the rows in the tableview and the count of the fetchedObjects array come out of sync, you can get this kind of crash.
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".