Core Data Part 2: Update, Delete Managed Objects and View Raw SQL Statement

71 Flares 71 Flares ×

This is the second article for our Core Data series. Previously, we gave you a brief introduction of Core Data and created a simple app to store all your device information. However, we only showed you how to insert records into data store through Core Data API and left out the update & delete operations.

In this tutorial, we’ll continue to work on the app and focus on the following areas of Core Data:

  • Updating or deleting an object using Core Data API
  • Viewing the raw SQL statement for debugging purpose

Updating or Delete an Object using Core Data

Note: If this is the first time you learn about Core Data, we recommend you to read the first tutorial. But for those who do not want to start from the very beginning, you can download this Xcode project to continue to work on the below tutorial.

In the last tutorial, we already discussed how to fetch and save a managed object using Core Data API. So how can you update or delete an existing managed object from database?

Deleting an Object

Let’s talk about the delete operation first. To allow user to delete a record from the table view, as you know, we can simply implement the “canEditRowAtIndexPath” and “commitEditingStyle” methods. Add the following code to the DeviceViewController.m:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}


- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSManagedObjectContext *context = [self managedObjectContext];

    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete object from database
        [context deleteObject:[self.devices objectAtIndex:indexPath.row]];
       
        NSError *error = nil;
        if (![context save:&error]) {
            NSLog(@"Can't Delete! %@ %@", error, [error localizedDescription]);
            return;
        }
       
        // Remove device from table view
        [self.devices removeObjectAtIndex:indexPath.row];
        [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }
}

We’ll not go into the details about how to remove a row from table view as we’ve already covered in our earlier tutorial. Let’s focus on the code of commitEditingStyle method for deleting the managed object from database.

Like saving data, we first grab the manage object context. The context provides a method called “deleteObject” that allows you to delete the specific object from database. Lastly, we invoke the “save” method to commit the change. Following the removal of the object from database, we also remove the record from the table view.

Now, let’s run the app and try to remove a record from database. Your app should look similar to the following:

Delete a device from database

Delete a device from database

Updating an Object

Next, we’ll enhance the app to let user update the device information. Go to the Storyboard and add a new segue for the table cell. This segue is used to connect a table cell and the detail view controller. When user selects any device in the table view, the detail view controller will be displayed to show the information of the selected device.

MyStore - Add UpdateDevice Segue

Add a new segue for updating device

To differentiate the segue from the one for adding a new device, we set an identifier as “UpdateDevice”. Next, add the prepareForSegue method in DeviceViewController.m:

1
2
3
4
5
6
7
8
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([[segue identifier] isEqualToString:@"UpdateDevice"]) {
        NSManagedObject *selectedDevice = [self.devices objectAtIndex:[[self.tableView indexPathForSelectedRow] row]];
        DeviceDetailViewController *destViewController = segue.destinationViewController;
        destViewController.device = selectedDevice;
    }
}

When user selects a specific device in the table view, it’ll go through the “UpdateDevice” segue. We then retrieve the selected device and pass it to the detail view controller.

Note: If you have no idea about what the segue is, go back to check out the tutorial about passing data between view controllers with segue.

Next, add a new properties in the DeviceDetailViewController.h for saving the selected device:

1
@property (strong) NSManagedObject *device;

As always, add the synthesis statement in the DeviceDetailViewController.m:

1
2
@implementation DeviceDetailViewController
@synthesize device;

To display the information of the selected device, we have to change the “viewDidLoad” method:

1
2
3
4
5
6
7
8
9
10
11
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    if (self.device) {
        [self.nameTextField setText:[self.device valueForKey:@"name"]];
        [self.versionTextField setText:[self.device valueForKey:@"version"]];
        [self.companyTextField setText:[self.device valueForKey:@"company"]];
    }

}

Let’s stop here and try to run the app again. As your app launches, tap any of the device records and the device information should appear in the detail view.

MyStore - Display Detail Device Info

Display Detailed Device Information

However, the app is not finished yet. If you try to edit the information of an existing device, it will not update the device information properly. Go back to the DeviceDetailViewController.m and modify the “save:” method:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
- (IBAction)save:(id)sender {
    NSManagedObjectContext *context = [self managedObjectContext];
   
    if (self.device) {
        // Update existing device
        [self.device setValue:self.nameTextField.text forKey:@"name"];
        [self.device setValue:self.versionTextField.text forKey:@"version"];
        [self.device setValue:self.companyTextField.text forKey:@"company"];

    } else {
        // Create a new device
        NSManagedObject *newDevice = [NSEntityDescription insertNewObjectForEntityForName:@"Device" inManagedObjectContext:context];
        [newDevice setValue:self.nameTextField.text forKey:@"name"];
        [newDevice setValue:self.versionTextField.text forKey:@"version"];
        [newDevice setValue:self.companyTextField.text forKey:@"company"];
    }
   
    NSError *error = nil;
    // Save the object to persistent store
    if (![context save:&error]) {
        NSLog(@"Can't Save! %@ %@", error, [error localizedDescription]);
    }
   
    [self dismissViewControllerAnimated:YES completion:nil];
}

We’ll update the device information if any of the devices is selected. If there is no selected device, we’ll then create a new device and add it into the database.

Try to test the app again. The update feature should now work properly:

MyStore - Update Device Info Sample

Now you can update the device info properly!

Viewing the Raw SQL Statement

Thanks to Core Data. Even without learning SQL and database, you’re able to perform create, select, update and delete operation. However, for those with database background, you may want to know the exact SQLs executed behind the scene.

To enable SQL output for debugging purpose, click “MyStore” and select “Edit Scheme”.

Xcode Edit Scheme

Edit scheme in Xcode project

Under “Argument Passed on Launch” section, click the “+” button and add the “-com.apple.CoreData.SQLDebug 1″ parameter:

Xcode add SQL Debug Parameter

Add SQL Debug Parameter

Click “OK” to confirm. Now run your app again and you’ll see the raw SQL statement (e.g. SELECT and UPDATE) displayed in the output window.

Sql statement output debug

SQL statement for Core Data Debugging

What’s Coming Next

We hope you enjoy the tutorial and have a better understanding about Core Data. For your reference, you can download the complete source code here.

In the later tutorials, we’ll talk about object relationship and show you how to optimize the app using NSFetchedResultsController.

You May Like These:

Get Free Chapters of Our AppCoda Book

Learn iOS 7 Programming from Scratch

The Learn iOS 7 Programming from Scratch is a 400-page eBook written for beginners with little or even no programming experience. It is based on the tutorials of our popular programming course. The book starts with the basics and walks you through the process to create iOS apps using iOS 7 SDK and Xcode 5. Want to learn more? Check it out here and get two free chapters.


Build Your Own Game and Monetize on the Side

Learn how to develop your first iOS game and make money on the side. The starter kit will come with full source code of a memory game for both iPhone and iPad, as well as, a complete guide to explain how the code works. Check out the starter kit to learn more.


  • Curlypaws

    Thanks very much Simon. It is really helpful to see the combination of storyboards and Core Data as so many of the example I’ve seen have been pre iOS5.

  • Arie

    I keep getting errors with – (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    if ([[segue identifier] isEqualToString:@”UpdateDevice”]) {
    NSManagedObject *selectedDevice = [self.devices objectAtIndex:[[self.tableView indexPathForSelectedRow] row]];
    DeviceDetailViewController *destViewController = segue.destinationViewController;
    destViewController.device = selectedDevice;
    }
    }

    • stuart

      I am also getting error in the same area

      • NameTest

        You must include ‘DeviceDetailViewController.h’ file to DeviceViewController.m.
        #import “DeviceDetailViewController.h”

  • Arie

    2012-12-25 17:51:28.604 MyStore[1967:c07] Unresolved error Error Domain=NSCocoaErrorDomain Code=134100 “The operation couldn’t be completed. (Cocoa error 134100.)” UserInfo=0xa057fa0 {metadata={

    NSPersistenceFrameworkVersion = 419;

    NSStoreModelVersionHashes = {

    Device = ;

    };

    NSStoreModelVersionHashesVersion = 3;

    NSStoreModelVersionIdentifiers = (

    “”

    );

    NSStoreType = SQLite;

    NSStoreUUID = “CAC08A0E-5C74-499B-BA50-A14AC5E803EA”;

    “_NSAutoVacuumLevel” = 2;

    }, reason=The model used to open the store is incompatible with the one used to create the store}, {

    metadata = {

    NSPersistenceFrameworkVersion = 419;

    NSStoreModelVersionHashes = {

    Device = ;

    };

    NSStoreModelVersionHashesVersion = 3;

    NSStoreModelVersionIdentifiers = (

    “”

    );

    NSStoreType = SQLite;

    NSStoreUUID = “CAC08A0E-5C74-499B-BA50-A14AC5E803EA”;

    “_NSAutoVacuumLevel” = 2;

    };

    reason = “The model used to open the store is incompatible with the one used to create the store”;

    }

    (lldb)

    • http://www.simonblog.com Simon Ng

      In the iOS simulator, click “iOS simulator” from the menu and select “Reset Content and Settings…”. Then try to build your project and run the app again. This may resolve the issue.

  • Marian

    Hi!
    I like your Tutorials very much. Thank you! I have an idea for a new tutorial, can you explain how to record the voice in an app?

    Marian

    • http://www.simonblog.com Simon Ng

      Great suggestion. I’ll put it in my todo list.

  • Bob

    I just got here from your previous post. As payback for your great article here is a tool I have found very helpful for understanding Core Data

    https://github.com/yepher/CoreDataUtility

  • Justin Bush

    Can you include iCloud compatibility in Part 3? Your tutorial’s have been very helpful, thanks a lot.

    • http://www.simonblog.com Simon Ng

      We’ll cover relationships of Core Data in the next tutorial. But it’s good suggestion. We’ll write one about iCloud in the future.

  • xcdr

    Thank you very much it is perfect tutorial

  • Redkigs

    Thanks a lot! This turial us exactlt what I’m looking for.

  • http://twitter.com/Sodooooo Sodbileg Gansukh

    That’s really good tutorial. Can you please show us how to sync Core Data with MySQL web services with relationship? I’ve already read syncing tutorial on Raywenderlich, but it looks too difficult for me.

  • Jumanji

    just want to say thank you very much this is a great tutorials!!! keep on posting !!!

  • Maciek Macie

    It’s not easy to find a table view + core data tutorial working on latest iOS. Thank you. I hope part 3 will be published soon

    • http://www.simonblog.com Simon Ng

      I am still editing part 3 but it should be available later this month. Stay tuned :-)

  • Wouter

    I feel like you’re intentionally leaving more and more little steps out during your tutorial, and then I get errors, but then I can fix them because of what I got from your earlier lessons!

    In this case for example, adding the segue gaven an error because he didn’t recognize the DeviceDetailViewController then, but of course importing the correct .h file at the top of DeviceViewController.m fixed that!

    Wonderful feeling :-)

  • sumy

    Thankz!!! Great Tutorial…..How can add image to core data in this application(along with each device)?

  • sumy

    How can add umage to core data in this appln( for each new device added)?

  • azma

    Great Tutorial. In the next one, maybe discuss how to allow re-ordering of the tableview cells, having a heck of a time with that.

  • pointer

    Excellent tutorial. Looking forward to seeing part 3.

  • Vladislav Kovalyov

    This is a really great and simple tutorials. But I met a problem. I create another view for edit my data. When I tap “save”, it saves edited data and show on my table view. But when I restart my app, it doesn’t save my changes. How can I fix it?

    P.S. Sorry for my bad English.

    • Tim

      Me too, did you find an answer to this?

  • Hugo

    Hi,

    First of all, two great introductions to Core Data ! I wish you’d write some more about relationships and iCloud sync.

    Anyway, I would like to know how the method save: is invoked if we are only checking if the data has been saved/removed by writing : if(![context save:&error]) { … } ???

    Thanks !

    • Crazy8s

      If you are still interested, it appears the -(BOOL)save: method both invokes the save and returns YES on completion. It is not simply a check to see if the record has already been saved.

  • Felix

    excellent tutorials! Please when will session 3 be available? Thanks

    • http://www.simonblog.com Simon Ng

      I’ve drafted the 3rd article but need some editing before releasing it here. Stay tuned.

      • Luwen Huang

        This is truly great stuff – the annotated graphics and explanations make these tutorials the best available online – can’t wait for the next article!

  • asaf

    Great tutorial

    Help me so much.

    but i have a problem with my assignment.

    i have an Students db (core data), i have one main view controller that contains the TableView with all context and Fetch.

    to add Student, i have addStudentViewController.

    the insert work great.

    But, i have an editStudentViewController, when i click on accessoryButtonTappedForRowWithIndexPath i send the relevant information but the Edited data not store.

    my question: how can i pass the nsmanagedObject to another viewController or how can i do the edit by another viewController.

    Thanks

  • Aamir khan

    best tutorials but sir only little information about database so you should to uploaded the complete set of the database tutorials………….

  • HLA

    Thanks a lot…
    I would like to know how to dismiss keyboard after typing text in text box.

  • Owen Andrews

    Fantastic tutorials! Beats Apples docs ;)

  • Robert

    Great guide for Core Data basics and complete source code that works too! Thanks, been searching all morning for a good tutorial.

  • Abrar

    Hey, awesome tutorial!! Really enjoyed it. I was wondering one more thing… what if I wanted to sort the results by device? so all the apples up top and the rest below. How would I go about doing that?

  • jacob banks

    i did both tutorials and at the end of this one i tried to run it and i got a black screen i have no errors or warnings can you help me.

    • shalin pandey

      Make Your StoryBoard as Main in project Setting…………

  • sankar ram

    Hey I got a error define the Identifier Please help me in this

  • Mạnh Hiền Lành

    thanks a lot, can you write about core data part 3 for series guide,it’s how to use coreData in the app, please!

  • pradeep

    Could somebody help me please ? I’m getting the below error when i’m trying to update the device details (i.e., when i select device in the table view). I’m using xcode 5. Additional point : I have embedded ‘navigation controller’ to the view controller.

    2014-02-27 00:54:54.537 MyStore[3595:70b] -[UINavigationController setDevice:]: unrecognized selector sent to instance 0x8c824b0

    2014-02-27 00:54:54.540 MyStore[3595:70b] *** Terminating app due to uncaught exception ‘NSInvalidArgumentException’, reason: ‘-[UINavigationController setDevice:]: unrecognized selector sent to instance 0x8c824b0′

    *** First throw call stack:

    (

    0 CoreFoundation 0x01aa05e4 __exceptionPreprocess + 180

    1 libobjc.A.dylib 0x018238b6 objc_exception_throw + 44

    2 CoreFoundation 0x01b3d903 -[NSObject(NSObject) doesNotRecognizeSelector:] + 275

    3 CoreFoundation 0x01a9090b ___forwarding___ + 1019

    4 CoreFoundation 0x01a904ee _CF_forwarding_prep_0 + 14

    5 MyStore 0x000043ba -[MSDeviceViewController prepareForSegue:sender:] + 458

    6 UIKit 0x00ac606c -[UIStoryboardSegueTemplate _perform:] + 156

    7 UIKit 0x00ac60f9 -[UIStoryboardSegueTemplate perform:] + 115

    8 UIKit 0×00673775 -[UITableView _selectRowAtIndexPath:animated:scrollPosition:notifyDelegate:] + 1453

    9 UIKit 0×00673924 -[UITableView _userSelectRowAtPendingSelectionIndexPath:] + 279

    10 UIKit 0×00677908 __38-[UITableView touchesEnded:withEvent:]_block_invoke + 43

    11 UIKit 0x005ae183 ___afterCACommitHandler_block_invoke + 15

    12 UIKit 0x005ae12e _applyBlockToCFArrayCopiedToStack + 403

    13 UIKit 0x005adf5a _afterCACommitHandler + 532

    14 CoreFoundation 0x01a684ce __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 30

    15 CoreFoundation 0x01a6841f __CFRunLoopDoObservers + 399

    16 CoreFoundation 0x01a46344 __CFRunLoopRun + 1076

    17 CoreFoundation 0x01a45ac3 CFRunLoopRunSpecific + 467

    18 CoreFoundation 0x01a458db CFRunLoopRunInMode + 123

    19 GraphicsServices 0x039019e2 GSEventRunModal + 192

    20 GraphicsServices 0×03901809 GSEventRun + 104

    21 UIKit 0x00591d3b UIApplicationMain + 1225

    22 MyStore 0x000052ed main + 141

    23 libdyld.dylib 0x020de70d start + 1

    24 ??? 0×00000001 0×0 + 1

    )

    libc++abi.dylib: terminating with uncaught exception of type NSException

    Program ended with exit code: 0

  • Tabish Sohail

    Thanks alot..such a nice tutorial..clearly explained step by step..

  • Marco Boldetti

    Hello, i have a question….
    if i want to load a Core Data database on a previously loaded data, as i make? Thank’s.

  • mark r

    My software errors on:

    [self.device setValue:self.nameTextField.text forKey:@"name"];

    in:

    if (self.device) {
    // Update existing device
    [self.device setValue:self.nameTextField.text forKey:@"name"];
    [self.device setValue:self.versionTextField.text forKey:@"version"];
    [self.device setValue:self.companyTextField.text forKey:@"company"];
    }

    What would be the preseason for this?

    • mark r

      I get the error on line return UIApplicationMain(argc, argv, nil, NSStringFromClass([EyePrescriptionTrackerAppDelegate class])); Does anyone have any ideas why is errors here when I press the button to update my core data? Any thoughts would be appreciated.

  • Quân Chùa

    thanks you very very very much for your tutorials.It helped me alot. I am so lucky to visit you site :)

    • http://www.appcoda.com/ Simon Ng

      Great to hear that :) Keep coming back. You’ll find even more tutorials in coming weeks.

  • ish3lan

    how lucky I am for finding this tutorial
    thanx for the help

  • Annapurna priya

    great tutorial.!! Explains Core Data very easily..:)
    But suppose i am getting data from server and inserting the server data in core data. Now what i want is that, when some new data comes from the server i will update my core data database. In that case what should i do??

  • Iris

    Hi! Great tutorial! They’re a big help. Though I’m still having trouble fully understanding the Objective C language, little by little, I’m gaining more confidence in iOS programming thanks to you. :) Maybe you could do a tutorial on Magical Record next? Hehe. I’ll look forward to it.

  • Ejiro Ogagarue

    how do you update the object from a button placed in the cell instead of using the table cell row to update the object i really need help in doing that

  • Gourav

    thanku bro…i did use yours source code..bt now i want know abt , how to perform many to many relationship in cvoredata …..

    yhnks

  • Venkatraman

    Can you please show us how to sync Core Data with MySQL web services with relationship? I’ve already read syncing tutorial on Raywenderlich, but it looks too difficult for me

  • rana

    when i click on data it goes to update view controller, but when i update data nd press save , it not comes back to list view controller..(data even updated on list vier controller,,)

    can anyone help me in this?

  • Ali E.

    Simon, I just want to say thank you! I’ve been looking for almost 3 days for Core Data tutorials, I saw many long ones but this one is the BEST ONE! Very simple! I highly recommend it for Core Data beginners. Thanks again! :)

    • http://www.appcoda.com/ Simon Ng

      Thank you for your kind words :)

  • Pingback: iPhone Interview Questions | iBlogs

71 Flares Twitter 12 Facebook 48 Google+ 11 LinkedIn 0 71 Flares ×