Core Data iOS, What is Core Data



Core Data iOS, What is Core Data

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

What is Core Data?
If We like to made anything beyond the most simplistic app for iOS, we shall require a direction to persist data.. Fortunately, Apple gives the Core Data framework, a persistence layer that productively controls the coordination of saving / updating / deleting data, as well as maintaining the integrity of data.

With Core Data, we specify the schema we like our data to conform to, and afterward made objects from that schema to process the CRUD operation on. We do not have to worry about what is going on at the level of actual database, as this is all abstracted away.

It is worthy noting that Core Data isn't itself as database. Bydefault, it sit on the top of SQLite3, a lightweight database baked into iOS. However, it can be installed to persist data to the document files or, in case of StackMob SDK, a URL services that persist the data else where.

Why Should We Learn Or Use Core Data?
Before Core Data, developer had to do task directly with SQLite3 to save develop data. This given several headaches; we had to write verbose SQL command and handle the logic’s for CRUD operation. We were also responsible for insuring the data we saved matched our schema. By the end of it all, we had in essence written our own persistence layer! Core Data handle all the heavy lifting for us. As we persist our data all logics are managed under the hood with optimal level of performance in brain.

Core Data have a only a few of the learning curve, which can advise developer who like to dive direct into building for its using. However, taking much time to addition an understanding of the Core Data fundamental will pay high ratio in the long execution, as it is a powerful tool that will activates us to made data driven and robust apps.

Deleting an Object

First we talk about the operation of delete. To permit the user to delete any data from the table view, as we know that, we can simply utilize the “commitEditingStyle” and “canEditRowAtIndexPath” functions. Add the given below code to the DeviceViewController.m:


Code –:

- (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 shall not go into the deep about how to delete a row from table view as we have already finished in our previous tutorial. Now Let us focus on the commitEditingStyle function code for removing the manage objects from the database.

Like the data saving, You first catch the context of manage object. The context gives a function called “deleteObject” that permits us to remove the particular objects from the database. Finally, you activate the “save” function to committed the changes. Given below is the removal of the objects from the database, You also delete the data from available table view.

Now, let us execute the apps and try to delete the data from database. Our apps should look same to the given below :

Delete device from database
Delete device from database

Updating the Objects

Next, we shall improve the apps to let user update the information of any devices. Go to the Storyboard and submit the new segue for the cell of table. This segue is used to link the cell of table and the information of view controller. When client select any devices from the table view, the details view controller will be shown to display the information of the devices which has been selected.
Img -Add a new segue for updating device

To differentiate the segue from the one for adding the new devices, you set the identifier like below “UpdateDevice”. Next, submit the prepareForSegue function in DeviceViewController.m:


Code – :


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 chooses a particular device from the table view, it will go through the “UpdateDevice” segue. You then recover the chosen devices and pass it to the view controller details.

Let us halt here and try to execute the apps again. As our apps launches, tap any of the devices record and the devices information should visible under detail view.

Now update device info properly
Now update device info properly


However, the apps are not completed yet. If we try to update the details of any existing devices, it will not edit the information of devices decently. So Go back to the DeviceDetailViewController.m and edit the “save:” function: 


No comments:

Post a Comment

Popular Posts