iOS Tutorial: How to pre-load and ingest data using core data–

Source: Internet
Author: User
Tags sqlite database

This is followed by a follow-up tutorial on the iOS Tutorial: Core Data Persistence Storage Essentials tutorial, which is also used in the last production.

In the last tutorial, we only made a data model, then we created a table view using the data from the data model, and we learned how to test the feasibility of the data model, and today we look at how to load or reference the existing data into our program when the application is launched.

Note that what we learned in the last tutorial is to load the data directly by manipulating the SQLite database, you can of course always use this method, but this tutorial teaches a more elegant and reasonable approach.

In the next section of the tutorial, we will discuss how to use Nsfetchedresultscontroller to optimize the way our app accesses data.

You can download it from here if you do not have the last good program.

Pre-load/ingest data

So how exactly do we store the data in the core database? There are two better options at the moment.

    1. The introduction of data from an external file when the app is launched is the introduction of data from external sources, such as SQLite databases or XML files, when the program starts running.
    2. Provide a completed SQLite database, first make a database model like the last tutorial said, then populate the model with data, the way to populate the data is to use a utility app, the utility app can be a use of the core data The API populates the database with a Mac or iOS app, or it can be a program that populates the database directly. Once the database is populated, you can set up a default database that is not used by the database without an existing database.

In this tutorial, we'll show you how to use a simple utility app to preload a well-installed core data database for your app to use in the second way.

The first step

The basis of our approach to using core data on iOS is consistent with what we use on Mac OS X, and they use the same models and classes.

This allows us to write a simple console program on Mac OS X to ingest data from a data source, and then bring this database database to our iOS program, right?

Let's try it, first open Xcode and use the command line Tool template in application in Mac OSX class.

Let's use "CoreDataTutorial2" as the name of the project, and remember "Core Data" and "Using Automatic Reference counting".

After the creation is complete, select "Coredatatutorial2.xcdatamodeld" to remove it completely.

Then find out which of the files we completed last

    • Failedbankcd.xcdatamodeld
    • FailedBankInfo.h
    • Failedbankinfo.m
    • FailedBankDetails.h
    • Failedbankdetails.m

Copy these files, or drag them directly into our new project:

Make sure that the Copy items into destination group ' s folder (if needed) is not selected

and check "Add to targets".

By choosing MAIN.M, you'll notice that because we've chosen to use core data, we've prepared some templates here, and now we're going to modify these methods to get them to generate data for our iOS program.

Move the managedObjectModel() method from

NSString *path = [[[Nsprocessinfo ProcessInfo] arguments] objectatindex:0];p ath = [path stringbydeletingpathextension];

Replaced by

NSString *path = @ "FAILEDBANKCD";

This will point to the program FailedBankCD.xdatamodeld rather than the one we have deleted CoreDataTutorial2.xdatamodeld .

Press Command+r to compile and run, you should see no errors.

But if you compile before this step, you will then have a data mismatch error, as we said in our last tutorial, delete and then recompile and run the line.

If you see the following error:

Nsinvalidargumentexception ', Reason: ' Cannot create an nspersistentstorecoordinatorwith a nil model '

This is because the program is looking for a ' momd ' file, (the previous version of the core data model), but if your app is not using this file, then this error, the quickest way to fix it is to change the Managedobjectmodel () method to the following:

Nsurl *modelurl = [nsurl fileurlwithpath:[path stringbyappendingpathextension:@ "Mom"];

It should be okay now.

Introducing Data

Now it's time to get to the play hardball guy and really load our data in.

In our example, we're going to introduce data from a JSON file, and maybe you want to introduce data from other types of files, but the principle is the same.

Below, we create a new file Ios–other–empty

Name this file Banks.json.

Enter the following code:

[{' name ': ' Bank1 ', ' City ': ' City1 ', ' state ': ' State1 ', ' zip ': 11111, ' closedate ': ' 1/1/11 '}, {' name ': ' Bank2 ', ' City ': "City2", "state": "State2", "zip": 22222, "closedate": "2/2/12"}, {"Name": "Bank3", "City": "City3", "state": "State3", "Zip": 33333, "closedate": "3/3/13"}, {"Name": "Bank4", "City": "City4", "state": "State4", "zip": 44444, "closedate": " 4/4/14 "}]

This is a JSON file with four dictionaries in an array, each with several attributes corresponding to the objects in the failedbankinfo/failedbankdetails.

If you are not quite sure how the JSON file organizes the data, you can take a look at this tutorial: this tutorial.

Next, we tell our application when compiling this file in our product catalog, look at the diagram do, first select project, then select the CoreDataTutorial2 target, select the Build Phase tab, press "ADD build Phase", select " Add Copy File ", select target location for" products Directory ", and finally," Banks. " Drag the JSON to the Add Files section.

When an app starts, it uses Failedbank's data model and class to initialize a database of core data and then uses the data from the Banks.json file to enter it.

Now, we want to:

    • Loading JSON files
    • Parse JSON file as a Objective C array
    • Enumerates the data in this array, creating a managed item for each object.
    • Deposit them all into Core Data

Start programming, first open the MAIN.M and add the following code to the main function:

    nserror* err = nil;    nsstring* DataPath = [[NSBundle mainbundle] pathforresource:@ "Banks" oftype:@ "json"];    nsarray* Banks = [nsjsonserialization jsonobjectwithdata:[nsdata Datawithcontentsoffile:datapath]                                                     options: Kniloptions                                                       error:&err];    NSLog (@ "Imported Banks:%@", Banks);

After that, your main function should look something like this:

 int main (int argc, const char * argv[]) {@autoreleasepool {        Create the Managed object context Nsmanagedobjectcontext *context = Managedobjectcontext ();        Custom code here ...//Save the Managed object context Nserror *error = nil; if (![ Context Save:&error]) {NSLog (@ "error while saving%@", ([error localizeddescription]! = nil)?            [Error localizeddescription]: @ "Unknown error");        Exit (1);        } nserror* err = nil;        nsstring* DataPath = [[NSBundle mainbundle] pathforresource:@ "Banks" oftype:@ "json"];                                                         nsarray* Banks = [nsjsonserialization jsonobjectwithdata:[nsdata Datawithcontentsoffile:datapath] Options:kniloptions error:&e        RR];    NSLog (@ "Imported Banks:%@", Banks);
 } return 0; 

This is using the built-in nsjsonserialization API to simply import the JSON file data into the core Foundation's data type Central (such as nsarray,nsdictionary, etc.), to learn more, see this Tutorial.

Run this program and you will see the following output:

2012-04-14 22:01:34.995 coredatatutorial2[18388:403] imported Banks: (        {City        = City1;        Closedate = "1/1/11";        name = BANK1;        state = State1;        Zip = 11111;    },        {city        = City2;        Closedate = "2/2/12";        name = BANK2;        state = State2;        Zip = 22222;    },        {city        = City3;        Closedate = "3/3/13";        name = Bank3;        state = State3;        Zip = 33333;    },        {city        = City4;        Closedate = "4/4/14";        name = BANK4;        state = State4;        Zip = 44444;    })

Now that we have been able to store this data in a Objective–c object, we can now enter the data into the database of core data as we did at the end of the last tutorial.

First add a reference to the file you need in the header:

#import "FailedBankInfo.h" #import "FailedBankDetails.h"

Then put these before you join the main function code.

[Banks enumerateobjectsusingblock:^ (id obj, Nsuinteger idx, BOOL *stop) {Failedbankinfo *failedbankinfo = [Nsentitydescription insertnewobjectforentityfo    rname:@ "Failedbankinfo" inmanagedobjectcontext:context];    Failedbankinfo.name = [obj objectforkey:@ "name"];    failedbankinfo.city = [obj objectforkey:@ "City"];    failedbankinfo.state = [obj objectforkey:@ "state"]; Failedbankdetails *failedbankdetails = [Nsentitydescription insertnewobjectfore    ntityforname:@ "Failedbankdetails" inmanagedobjectcontext:context];    Failedbankdetails.closedate = [NSDate datewithstring:[obj objectforkey:@ "Closedate"];    Failedbankdetails.updatedate = [NSDate Date];    Failedbankdetails.zip = [obj objectforkey:@ "zip"];    Failedbankdetails.info = Failedbankinfo;    Failedbankinfo.details = failedbankdetails;    Nserror *error; if (![ ContExt Save:&error]) {NSLog (@ "Whoops, couldn ' t Save:%@", [Error localizeddescription]); }}];//Test listing all Failedbankinfos from the storensfetchrequest *fetchrequest = [[Nsfetchrequest alloc] init];                                          Nsentitydescription *entity = [nsentitydescription entityforname:@ "Failedbankinfo" Inmanagedobjectcontext:context]; [Fetchrequest setentity:entity]; Nsarray *fetchedobjects = [Context executefetchrequest:fetchrequest error:&error];for (FailedBankInfo *info in    fetchedobjects) {NSLog (@ "Name:%@", info.name);    Failedbankdetails *details = info.details; NSLog (@ "ZIP:%@", details.zip);}

This code is essentially the code we used last time, except for the way we used the Enumerateobjectsusingblock: Old enumeration of the contents of this array after inserting, and then we use a FETCH command to output the data.

Now run it, and you'll see the output of the previous array.

2012-04-14 22:15:44.149 coredatatutorial2[18484:403] name:bank12012-04-14 22:15:44.150 CoreDataTutorial2[18484:403] Zip:111112012-04-14 22:15:44.150 coredatatutorial2[18484:403] name:bank22012-04-14 22:15:44.151 CoreDataTutorial2[ 18484:403] zip:222222012-04-14 22:15:44.152 coredatatutorial2[18484:403] name:bank32012-04-14 22:15:44.152 COREDATATUTORIAL2[18484:403] zip:333332012-04-14 22:15:44.153 coredatatutorial2[18484:403] name:bank42012-04-14 22:15:44.153 coredatatutorial2[18484:403] zip:44444

Ok, these are the data you have in core. In addition to this simple JSON file, you can also use more complex JSON files, XML files, even ordinary table files, as long as you save as a CSV format, can also be from the Internet pipe, can use the number of file types are not clear, we will be detailed in the future.

Xcode's sick?

Let's take a brain transplant and transfer our database using the command-line program on Mac OS x to the iphone app. The simplest way to find a database file is to right-click (Ctrl +) the CoreDataTutorial2 product and press "Show in Finder".

This will open a new Finder window, which will have these files:

    • banks.json– This is the original file of the data, remember?
    • coredatatutorial2– This is the application itself.
    • FAILEDBANKCD.MOMD (or. Mom) – This is the compiled core data model.
    • coredatatutorial2.sqlite– This is the SQLite database file we're looking for, which is generated by the program, and Core data should be generic. You can find a SQLite database of the viewing software, you can also download this

OK "Coredatatutorial2.sqlite" is the file that I need, below we copy this file to our previous tutorial source project file, then open:

Drag and drop the "coredatatutorial2.sqlite" file from the Finder into Xcode's project to ensure that the "Copy items into Destination Group's folder (if needed)" option is not selected , and the other is selected.

Finally, open "FBCDAPPDELEGATE.M", locate the persistentStoreCoordinator method, and add the following code to the following NSURL *storeURL = [[self app... line:

if (![ [Nsfilemanager Defaultmanager] Fileexistsatpath:[storeurl Path]] {    Nsurl *preloadurl = [Nsurl fileurlwithpath:[[ NSBundle Mainbundle] pathforresource:@ "CoreDataTutorial2" oftype:@ "SQLite"];    nserror* err = nil;    if (![ [Nsfilemanager Defaultmanager] Copyitematurl:preloadurl tourl:storeurl Error:&err]) {        NSLog (@ "Oops, could Copy preloaded Data ");}    }

This section of the code is to detect whether the SQLite database is already existing with the app, if it does not exist, it will find our pre-loaded database, and then copy the database to the normal path, super simple, let's try!

See the original in the JSON file four banks, and then there is a we added in the first tutorial test Bank, if you do not see, probably is the database already exists, the Camellia simulator after the app rerun.

What do you see later?

This is the example of my production process source code, welcome to download.

This is the original author's sample program: here (direct download)

Please pay attention to my scarf: @Oratis

On the Oratis and the watercress, my name is the same.

I'll share the tutorials I've published later in these social networks.

If you have any questions, welcome to the bottom of the message, also welcome to write to me, my e-mail address is: [email protected]

iOS Tutorial: How to pre-load and ingest data using core data–

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.