Luke
Luke

Reputation: 9700

Core Data isn't saving anything, but not giving an error?

I'm trying to recreate the absolute simplest Core Data example I could find, and I've still managed to run into a problem. It seems the SQLite database is being created in line with my Entity, but no actual data is being added to it. Here's my .h file:

#import <CoreData/CoreData.h>
#import "AppDelegate.h"

@interface MainViewController : UIViewController

@property (strong, nonatomic) NSManagedObjectContext *managedObjectContext;

- (IBAction) createDatabase;

@end

And here's my .m:

#import "MainViewController.h"

@implementation MainViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
}

- (IBAction) createDatabase
{
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    _managedObjectContext = [appDelegate managedObjectContext];

    NSManagedObject *myMO = [NSEntityDescription insertNewObjectForEntityForName: @"Book" inManagedObjectContext: _managedObjectContext];

    [myMO setValue: [NSNumber numberWithInt: 123] forKey: @"bookID"];
    [myMO setValue: @"Example book." forKey: @"book"];
    [myMO setValue: @"Example author." forKey: @"author"];
    [myMO setValue: @"Example category." forKey: @"category"];
    [myMO setValue: [NSNumber numberWithBool: NO] forKey: @"isLiked"];
    [myMO setValue: [NSNumber numberWithBool: NO] forKey: @"isDisliked"];
}

@end

I can't figure out what I'm doing wrong. Xcode creates the .sqlite file in the Documents directory of the app when I launch it, but hitting the button to call createDatabase doesn't cause any of the text ("Example book."), etc. to be entered into the SQLite file at all.

Am I doing something wrong? This code is pretty much copied and pasted, so I really don't know what I've done wrong.

Upvotes: 0

Views: 106

Answers (1)

DivineDesert
DivineDesert

Reputation: 6954

I cant find any thing in your code that saves your changes. It should be something like

 if (![myMO save:&error]) {
    NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
 }

Refer this link for more help

  1. http://developer.apple.com/library/ios/#documentation/DataManagement/Conceptual/iPhoneCoreData01/Introduction/Introduction.html
  2. http://www.raywenderlich.com/934/core-data-on-ios-5-tutorial-getting-started
  3. https://blog.stackmob.com/2012/11/iphone-database-tutorial-part-1-learning-core-data/

Upvotes: 2

Related Questions