The program is very simple: it has a masterView and a detailView. In the detail view I should be able to edit the attributes from the corresponding object (basically adding a number to the already stored number). The problem is that I'm not sure how to save the changes.
I have this in an IBAction in the detailViewController:
- (IBAction)depositFunds:(id)sender
{
float change = [[self.detailItem valueForKey:#"balance"] floatValue] + [amountTextfield.text floatValue];
[self.detailItem setValue:[NSNumber numberWithFloat:change] forKey:#"balance"];
}
How can I save those changes?
I just tried importing the managedObjectContext from the masterView and saving it. It worked.
Do this, import the context:
- (void) setManagedObject:(NSManagedObjectContext *)managedObject
{
managedObjectContext = managedObject;
}
Pass the context through either the segue method or didSelectRowAtIndex method.
myDetailViewController *viewC = [segue destinationViewController];
[viewC setManagedObject:self.managedObjectContext];
Then add this to your saving method.
NSError *error = nil;
if (![managedObjectContext save:&error])
{
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
Cheers!
Related
I'm having some issues getting Core Data to save new rows that I add when using a UITextField. Here is my method for inserting objects into my table view. What should happen is when I click the add button, a textfield should be added, and then go right into edit mode. Then when the user clicks done on the keyboard the textfield should end editing and then the textfield should save the entry into core data.
Edit: removed call to textFieldDidEndEditing in the insertNewObject:(id)sender method. It was crashing the app
- (void)insertNewObject:(id)sender {
NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];
TehdaItem *item = [NSEntityDescription insertNewObjectForEntityForName:#"TehdaItem" inManagedObjectContext:context];
// If appropriate, configure the new managed object.
// Normally you should use accessor methods, but using KVC here avoids the need to add a custom class to the template.
// Putting the cell in edit mode
TehdaTableViewCell *editcell;
for (TehdaTableViewCell *cell in [self.tableView visibleCells]) {
if (cell.itemLabel.text == item.itemTitle) {
editcell = cell;
break;
}
}
[editcell.itemLabel becomeFirstResponder];
// The cell needs to call the method textfield did end editing so that it can save the new object into the store
// Save the context.
NSError *error = nil;
if (![context 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.
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
}
Here is my textFieldDidEndEditing method:
- (void)textFieldDidEndEditing:(UITextField *)textField {
TehdaTableViewCell *cell = (TehdaTableViewCell *) textField.superview.superview;
TehdaItem *item = [self.fetchedResultsController objectAtIndexPath:[self.tableView indexPathForCell:cell]];
//TehdaTableViewCell *cell;
item.itemTitle = cell.itemLabel.text;
}
Not really sure where to go from here. Any help would be appreciated.
Thanks.
You can use
NSError *error;
[item.managedObjectContext save:&error];
if (error) {
// Triage the problem and respond appropriately
}
in the - (void)textFieldDidEndEditing:(UITextField *)textField method. But if I were you I'd do some validation before you save the object.
Hey all, been scratching my head at this for a couple of days now, but still have no idea how to do it.
I have an UIButton, by clicking it I would like it to add data to my Core Data model. At the moment I'm using navigationItem.rightBarButtonItem = addButton; from my Core Data UITableViewController to add data, but instead I like to connect a UIViewController to the core data model and have an UIButton add data to it.
For example, when this UIbutton is click, it would change to another view while also adding data to the core data model.
-(IBAction)changeviewandadddata {
SecondViewController *screen = [[SecondViewController alloc] initWithNibName:nil bundle:nil];
screen.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
[self presentModalViewController:screen animated:YES];
[screen release];
}
Any help or suggestions on how to do this would be appreciated.
Here is a sample to insert data into a Core Data store.
NSManagedObject *object = [NSEntityDescription insertNewObjectForEntityForName:#"EntityName"
inManagedObjectContext:managedObjectContext];
[object setValue:#"test" forKey:#"something"];
NSError *error = nil;
if (![managedObjectContext save:&error]) {
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
//handle the error
[managedObjectContext rollback];
}
I can't figure out how come the row count is correct but the uitableview won't load the row contents the NSLog shows carresults=(null), but the row count is correct, on the simulator if I relaunch, the carresults get filled. It seems like I'm missing my first fetchedResultsController teh first time through, but how can it get the row count if it doesn't know what' there?
Help!! any Ideas? Thanks, Mike
The titleForHeaderInSection works fine, brings back the correct titles:
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
return [[[fetchedResultsController1 sections] objectAtIndex:section] name];
}
This brings back the correct row count:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
id <NSFetchedResultsSectionInfo> sectionInfo = [[fetchedResultsController1 sections] objectAtIndex:section];
return [sectionInfo numberOfObjects];
}
This does not populate the cells until a rebuild on simulator, never populates the iPhone.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *FirstViewIdentifier = #"FirstViewIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:FirstViewIdentifier];
if (cell == nil) {
[[NSBundle mainBundle] loadNibNamed:#"Cell" owner:self options:nil];
cell = firstviewCell;
self.firstviewCell = nil;
}
Cars *carresults = (Cars *)[fetchedResultsController1 objectAtIndexPath:indexPath];
NSLog(#"carresults %#", carresults.make);
EDIT: Here is the FRC:
NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:[[[UIApplication sharedApplication] delegate] managedObjectContext] sectionNameKeyPath:#"key" cacheName:#"Root1"];
self.fetchedResultsController = aFetchedResultsController;
fetchedResultsController.delegate = self;
Since you haven't provided any debug info I can only guess as to what's wrong, so I'll ask you some questions. Does it in fact instantiate the firstviewCell property with the nib. If the cell is not connected to the firstviewCell property of the File Owner (in the nib) it won't work. Otherwise if the fetchedResultsController doesn't have anything in it you'll get an error if you try to access the data. If the nslog fires then you probably didn't get an error, which means that your Cars objects are being fetched theres just nothing in them. to see whats in the fetchedResultsController call NSLog(#"Fetched Objects: %#",[[fetchedResultsController fetchedObjects] description]); Keep in mind though, that fetchedObjects is only updated when you call performFetch. Since you say carresults gets filled when you restart the app it may be possible that you need to call saveContext for the results to get loaded. The only reason for this is if you create the data at runtime, before the table view gets loaded. Otherwise I would assume you have the table view set as the fetched results controller's delegate so that it gets informed of any changes and responds appropriately. The app delegate usually does this on applicationWillResign active or applicationWillTerminate (applicationWillTerminate doesn't seem to get called by iOS4 during normal closing).The only other thing I could think of is that maybe your SectionInfo object might contain the wrong information, try debugging that too.
Good Luck,
Rich
Edit: I appologize, the save context method is a method added to your appdelegate when you create an app based on core data. a good way to make a core data stack is to wrap it in an NSObject, it can be useful to make it a singleton ,unless of course you need concurrency in which case it gets really complicated. This is the implementation including the save context function:
// CoreDataStack.h
// do not call alloc, retain, release, copy or especially copyWithZone: (because I didn't bother to override it since you shouldn't try to create this in anything but the main thread, and definatly don't dispatchasync this object's methods)
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
#define kYourAppName #"This should be replaced by the name of your datamodel"
#interface CoreDataStack : NSObject {
#private
NSManagedObjectContext *managedObjectContext_;
NSManagedObjectModel *managedObjectModel_;
NSPersistentStoreCoordinator *persistentStoreCoordinator_;
}
#property (nonatomic, retain, readonly) NSManagedObjectContext *managedObjectContext;
#property (nonatomic, retain, readonly) NSManagedObjectModel *managedObjectModel;
#property (nonatomic, retain, readonly) NSPersistentStoreCoordinator *persistentStoreCoordinator;
+ (CoreDataStack *)sharedManager;
+ (void)sharedManagerDestroy;
// call this in your app delegate in applicationWillTerminate and applicationWillResignActive
- (void)saveContext;
- (NSURL *)applicationLibraryDirectory;
#end
// CoreDataStack.m
#import "CoreDataStack.h"
#interface CoreDataStack ()
- (oneway void)priv_release;
#end
#implementation CoreDataStack
static CoreDataStack *sharedManager = nil;
+ (CoreDataStack *)sharedManager {
if (sharedManager != nil) {
return sharedManager;
}
sharedManager = [[CoreDataStack alloc] init];
return sharedManager;
}
+ (void)sharedManagerDestroy {
if (sharedManager) {
[sharedManager priv_release];
sharedManager = nil;
}
}
- (id)retain {
return self;
}
- (id)copy {return self;}
- (oneway void)release{}
- (oneway void)priv_release {
[super release];
}
- (void)saveContext {
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.
*/
//abort();
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error"
message:#"The app has run into an error trying to save, please exit the App and contact the developers. Exit the program by double-clicking the home button, then tap and hold the iMean icon in the task manager until the icons wiggle, then tap iMean again to terminate it"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
[alert release];
}
}
}
#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_;
}
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:#"kYourAppName" withExtension:#"momd"];
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_;
}
NSString *yourAppName = [[NSString stringWithFormat:#"%#.sqlite",kYourAppName] autorelease];
NSURL *storeURL = [[self applicationLibraryDirectory] URLByAppendingPathComponent:yourAppName];
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();
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error"
message:#"The app has run into an error trying to load it's data model, please exit the App and contact the developers. Exit the program by double-clicking the home button, then tap and hold the iMean icon in the task manager until the icons wiggle, then tap iMean again to terminate it"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
[alert release];
}
return persistentStoreCoordinator_;
}
#pragma mark -
#pragma mark Application's Library directory
/**
Returns the URL to the application's Documents directory.
*/
// returns the url of the application's Library directory.
- (NSURL *)applicationLibraryDirectory {
return [[[NSFileManager defaultManager] URLsForDirectory:NSLibraryDirectory inDomains:NSUserDomainMask] lastObject];
}
#pragma mark -
#pragma mark Memory management
- (void)dealloc {
// release and set all pointers to nil to avoid static issues
[managedObjectContext_ release];
managedObjectContext_ = nil;
[managedObjectModel_ release];
managedObjectModel_ = nil;
[persistentStoreCoordinator_ release];
persistentStoreCoordinator_ = nil;
[super dealloc];
}
#end
I want to reset the data store clean by removing the app's sqlite file. I wrote this function in my data helper class:
-(void) resetPersistenStore {
NSError *error = nil;
[persistentStoreCoordinator_ release];
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:#"MyApp.sqlite"];
[[NSFileManager defaultManager] removeItemAtURL:storeURL error:&error];
if (error) {
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
}
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();
}
managedObjectModel_ = nil;
}
I put this following test in UIApplication::didFinishLaunchingWithOptions
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
/* test */
[TestDataHelper populateTestData:[self managedObjectContext]];
[TestDataHelper populateTestData:[self managedObjectContext]];
[self resetPersistenStore];
[TestDataHelper populateTestData:[self managedObjectContext]];
[TestDataHelper testPopulateTestData:[self managedObjectContext]];
Instead of one set of data created by the function populateTestData, I can see actually three set of data (because I called the function three times)
It is clear that resetPersistenStore() works, because without it, the data will keep accumulating.
So my question is:
Why the reset does not take effect immediately?
I have set managedObjectContext to nil in the reset function, but it did not help.
Here is my populateTestData function
+(void)populateTestData:(NSManagedObjectContext*)managedObjectContext {
Stock* s1 = (Stock*)[NSEntityDescription insertNewObjectForEntityForName:#"Stock"
inManagedObjectContext:managedObjectContext];
s1.code = #"ABC2";
s1.name = #"ABC";
s1.enteredBy = #"akong";
[managedObjectContext save:&error];
if (error) {
NSLog(#"Data error %#", [error description]);
} else {
NSLog(#"Init completed");
}
}
Even though the context saved the data in populateTestData, it still has data loaded in it.
Suppose when the application starts, the file has 3 objects. Now the first populateTestData message adds an object into the context, and save it. So 4 objects in the file, 1 in the context. After the second message, 5 in the file, 2 in the context. Now the file is gone, but still there are 2 in the context. Now the final message adds another object to the context and to the file, so there are 3 objects.
You said setting managedObjectContext to nil in the reset function didn't help. I doubt if the context has been properly reset there. Try [managedObjectContext reset] instead.
I am only speculating here but are you by any chance using a fetchedResultsController to verify/display the results of these operations? If so try to set its caching to nil and see if it helps.
NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:#"xxxxxxxx" cacheName:nil];
Cheers,
Rog
It may simply be an artifact of the simulator. If you're running in the simulator, you may need to reset it. From the iOS Simulator menu, select Reset Content and Settings...
Two hopefully minor questions regarding CoreData that I've been unable to find answers to:
1) I have a faulted object. Accessing an attribute as a property is not firing the fault, accessing the same property via KVC IS firing the fault. Any idea why?
i.e. object.title returns nil and object is still faulted, but [object valueForKey:#"title"] returns the title and the object is no longer a fault.
2) Updates to existing records have stopped working. Add/Delete works. Add/Update share the same code path (one is passed the existing object, the other a newly inserted object). However Update wont work. The data in the updated object is correct and set to the new values and the save succeeds with no errors, but the record in the database remains unchanged. Any idea?
NB: There is only one NSManagedObjectContext
Cheers
couldn't tell much from your description without code.
however it looks like you have updated the object in ram but the update wasn't submitted to the database layer making the physical change.
EDIT:
Yes, "Add" and "Delete" is different from "edit/update" a record.
for performance reason mapped objects are saved in memory as entities when you doing manipulation against NSManagedObjectContext you are not coding against database entirely.
check the link below:
http://cocoawithlove.com/2010/02/differences-between-core-data-and.html
normal work flow:
load appropriate rows from a database
instantiate objects from these rows
make changes to the graph objects
that are now in memory
commit the changes back to the
database
This is my core data for saving.
AppDelegate *app = (AppDelegate*)[[UIApplication sharedApplication] delegate];
Tweet *newTweet = (Tweet *)[NSEntityDescription insertNewObjectForEntityForName:#"Tweet" inManagedObjectContext:app.managedObjectContext];
newTweet.status = status;
newTweet.post_date = theDate;
newTweet.post_id = post_id;
newTweet.sent_error = sent_error;
newTweet.sent_status = sent_status;
newTweet.screen_name = [Settings getActiveScreenName];
// SAVE
NSError* error = nil;
if (![app.managedObjectContext save:&error]) {NSLog(#"did this work?? = %# with userInfo = %#", error, [error userInfo]);}
I have this in my app delegate
- (void)applicationWillTerminate:(UIApplication *)application {
// need to check if TweetViewController is activel.
// User is writing a tweet.
UIViewController * topController = [navigationController visibleViewController];
if([topController isKindOfClass:[TweetViewController class]] ){
[Settings setObject:[(TweetViewController*)topController tweetText].text forKey:#"last_tweet_text"];
}
NSLog(#"good bye");
NSError *error;
if (managedObjectContext != nil) {
if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
// Handle error.
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
exit(-1); // Fail
}
}
}
and this as well in AppDelegate
/**
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;
}
// ~/Library/Application Support/iPhone Simulator/User/
NSURL *storeUrl = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory] stringByAppendingPathComponent: #"tweetv12.sqlite"]];
NSError *error;
persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel: [self managedObjectModel]];
if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:nil error:&error]) {
// Handle error
NSLog(#"cannot save data, change db name.");
}
return persistentStoreCoordinator;
}
I am also able to save delete and update data with this.