iOS

Introduction to Core Data: Your First Step to Persistent Data


Editor’s note: After we published the tutorial about saving data in plist file, some readers asked about Core Data and how we can use it to save persistent information. This week, we work with Ziad Tamim, an independent iOS developer, to give you an introduction of Core Data and work with you to build a sample app using Core Data.

This tutorial talks about persistence on iPhone (or other iOS devices). What I mean by persistence is to make data that’s in your apps stay around between application launches. Persistence lets users store persistent data and also retrieve it, so that users don’t have to reenter all their data each time they use their applications. There are multiple ways to store data in iOS devices but most of them aren’t good enough to store a complicated data. They are usually used to save settings or to preload some data such as “Property List” and “Archiving Objects”. So that’s why we’ll go through Core Data to see how you can utilize it to manage data in database.

The focus of the tutorial is to provide a practical introduction of Core Data framework. I expect you’ve already gone through our tutorials about Storyboard and UITableView. I will not give in-depth explanation about how to create view controller in Storyboard but you can always refer to the earlier tutorials to gain better understanding.

Core Data is not a Database

When we talk about persistent data, people probably think of database. If you are familiar with Oracle or MySQL, you know that relational database stores data in the form of table, row and column, and it usually facilitates access through what-so-called SQL query. However, don’t mix up Core Data with database. Though SQLite database is the default persistent store for Core Data on iPhone, Core Data is not a relational database. It is actually a framework that lets developers store (or retrieve) data in database in an object-oriented way. With Core Data, you can easily map the objects in your apps to the table records in the database without even knowing any SQL.

To illustrate the concept, let’s begin and create your first app using Core Data. This app is called My Store. It is a very simple app that stores all devices you have by collecting the name, version, company.

MyStore App using Core Data

MyStore App using Core Data

Creating a Sample App with Core Data

First let’s create a project with Core Data. Open Xcode and create a new Project, choose the template Empty Application as shown below.

Create a New Project with Empty Application Template

Create a New Project with Empty Application Template

At the next screen, enter MyStore as a name of the project, select iPhone in Devices family and don’t forget to select the options Use Storyboards, Use Core Data, Use Automatic Reference Counting. Press next and create.

MyStore Xcode Project Options

Set up Xcode Project Options – Remember to select Use Core Data

Core Data Stack

Before we start working on the project, you first have to understand the Core Data Stack:

Managed Object Model – It describes the schema that you use in the app. If you have a database background, think of this as the database schema. However, the schema is represented by a collection of objects (also known as entities). In Xcode, the Managed Object Model is defined in a file with the extension .xcdatamodeld. You can use the visual editor to define the entities and their attributes, as well as, relationships.

Persistent Store Coordinator – SQLite is the default persistent store in iOS. However, Core Data allows developers to setup multiple stores containing different entities. The Persistent Store Coordinator is the party responsible to manage different persistent object stores and save the objects to the stores. Forget about it you don’t understand what it is. You’ll not interact with Persistent Store Coordinator directly when using Core Data.

Managed Object Context – Think of it as a “scratch pad” containing objects that interacts with data in persistent store. Its job is to manage objects created and returned using Core Data. Among the components in the Core Data Stack, the Managed Object Context is the one you’ll work with for most of the time. In general, whenever you need to fetch and save objects in persistent store, the context is the first component you’ll talk to.

The below illustration can probably give you a better idea about the Core Data Stack:

Core Data Stack

Core Data Stack

Defining Managed Object Model

Let’s move on to build the app. The first step is to open the Data Model named MyStore.xcdatamodeld and define the object model. Here we’ll define a Device entity that will be used to store the device information to database. To create an entity, click the + button in the bottom-left of the editor view and name the entity as Device.

Managed Object Model - Add Entity

Add Device entity in the model

Once you create a new entity, you need to add attributes to it. Click on the + button in the attributes section to do that. Add three attributes including name, version and company. Set the type as String.

MyStore Add Entity

Add 3 Attributes (company, name and version) to the Device entity

Designing the User Interface

Note: While we encourage you to build the user interface, you can also skip the procedures and download the project template from here. The template already comes with the Storyboard and set up all the view controller classes for you. This gives you a good starting point to work on Core Data. If you use the template, you can skip this section and go directly to the “Diving Core Data” section.

The next thing we need to do is to create the Storyboard that defines the views of our app. Navigate to File > New > New File and choose Storyboard in the User Interface template. Click next and select the iPhone device family, click create.

Creating the Storyboard

Creating the Storyboard

Once created, make sure to set the “Storyboard” you’ve just created as the main storyboard in the project setting.

MyStore Set Main Storyboard

Set the Storyboard you just created as the Main Storyboard

Also don’t forget to delete all the generated code in the method -(BOOL)application:application didFinishLaunchingWithOptions:launchOptions inside the AppDelegate file. The method should be as simple as this:

Go to Storyboard and create the user interface like below:

MyStore - Storyboard

MyStore App – Storyboard

First, drag a Table View Controller and embed it in a Navigation Controller. Drag a button to the top-right part of navigation bar and set the identifier as “Add”. This will automatically change the button to a “+” button. Next, select the prototype cell and change its style to “Right Detail”.

MyStore App - Table View Controller

Creating the Table View Controller

Drag a View Controller to the Storyboard and add a Navigation Bar to the top of the screen. Next, drag two buttons into the navigation bar. Name one as “Cancel” and the other one as “Save”. In the content view, add three text fields and name the placeholder attributes as “Name”, “Version” and “Company”.

This detail view will be shown when user taps the “+” button in the table view controller. So finally, press and hold the Control key, click the “+” button and drag towards the detail view controller. Select “Modal” as the Segue action to connect the table view controller and detail view controller.

MyStore App - Detail View Design

Designing the Detail View Controller

Creating View Controller Classes

Create a new class by right-clicking on the MyStore folder > New File > Objective-C class, and name the class as DeviceViewController. Make it as a subclass of UITableViewController. Navigate to the Storyboard, select the Table View Controller and associate it with the DeviceViewController class.

MyStore - Assign DeviceViewController Class

Set the Custom Class as DeviceViewController

Once done, do the same steps to create a new class named DeviceDetailViewControllerUIViewController. Again, go to Storyboard and set the custom class of the detail view controller as the “DeviceDetailViewController”.

Lastly, wire up the UITextFields to the DeviceDetailViewController header file and create two action methods for the save and cancel buttons respectively.

MyStore - Wire up Text Field

Creating IBOutlet and Action Methods

Your code should like this:

Diving into Core Data

With the user interface, it’s time to go into the details of Core Data. Apparently, there are a couple of areas we have to implement:

  1. Save device information in the Detail View Controller
  2. Fetch device information from persistent store (i.e. SQLite database) and populate the data into Table View Controller

We’ll look into the implementation one by one.

Saving Device Information

First, we need to implement the DeviceDetailViewController to let user add the devices to the database. Open up the DeviceDetailViewController.m file and add the following code after @implementation DeviceDetailViewController:

Recalled that we’ve selected the Core Data option when creating the project, Xcode automatically defines a managed object context in AppDelegate. This method allows us to retrieve the managed object context from the AppDelegate. Later we’ll use the context to save the device data.

Next, we’ll implement the “save” and “cancel”, add the necessary code to look like this:

When user taps the “Cancel” button, we expect the app to close the detail view controller. Line 2 of the above code invokes the dismissViewControllerAnimated method to dismiss the current view controller with animation.

For the “save” method, we first grab the managed object context. Every object that Core Data stores is inherited from NSManagedObject. So we first create a new instance of NSManagedObject for the “Device” entity that we’ve defined in the object model. NSEntityDescription class provides a method named “insertNewObjectForEntityForName” for developer to create a managed object. Once you created the managed object (i.e. newDevice), you can set the attributes (name, version, company) using the user input. Lastly, we call up the “save:” method of the context to save the object into database.

You can now hit the Run button to try out your app. Tap the “+” button to bring up the Detail View and save a new device. However, the new device is not yet displayed in the table. Let’s move on to see how you can fetch the device information from database.

Fetching Device Information

Open DeviceViewController.m, add a “devices” property to it so we can save all the devices received.

Again, add the following code after “@implementation DeviceViewController” for grabbing the managed object context:

Next, add a viewDidAppear method:

Like what we’ve done in the Detail View Controller, we first grab the managed object context. To fetch device information from database, the code above creates a new instance of NSFetchRequest and set the entity Device and invokes “executeFetchRequest” method to retrieve all the devices from the database. If you are familiar with relational databases, this instance works like the SELECT clause.

Note: If you’re new to viewDidAppear method, it is a method that will be called automatically every time a view is displayed. It’s unlike the viewDidLoad method that is invoked once when the controller is loaded.

Populating Device Information into Table View

As we would like to display these data into the table view we need to implement the data source of it, to do that add the below code:

If you have used UITableViewController before, the code above is the simple way to display data into the table view. If you check the code you will notice the NSMangedObject is pretty much like NSDictionary. It gathers all the attributes of the entity (i.e. Device) and you can simply use the “valueForKey” method to grab the attribute value.

Note: If you’re new to UITableView, you can check out the earlier tutorials about UITableView.

That’s it. Let’s try to run the app and test it. If everything is okay, your app should like this. Try to add some devices and the device information should be populated automatically in the table view.

MyStore App using Core Data

MyStore App using Core Data

What’s Coming Next

It’s a lengthy tutorial but we try to elaborate the implementation as detail as possible so everyone can follow. As you can see, with Core Data, you don’t have to care about SQL to save and retrieve data from database. Everything is done behind the scene. This tutorial kicks off the first part of Core Data series. Later we’ll talk more about object relationship.

Lastly, let me end the tutorial with an exercise. Try to complete the app by adding the functions that let user update and delete an existing device by selecting a row in the table view.

Hope you enjoy the tutorial and feel to leave us comment.

Update: Check out part 2 of the Core Data tutorial series!

iOS
Function Naming in Swift
iOS
Adding Local Notifications in Your iOS App
iOS
Understanding XML and JSON Parsing in iOS Programming
  • Curlypaws

    CurlypawsCurlypaws

    Author Reply

    This is really good – but in trying to add update and delete capabilities I’m struggling to find out how I’d identify the correct record and then update/delete it. After all, there is nothing that makes sure the entries are unique. Should I be looking at NSFetchedResultsController?


  • Paranoid

    ParanoidParanoid

    Author Reply

    It’s a great core data tutorial, thx.


  • Bob

    BobBob

    Author Reply

    Thanks for the article on Core Data. It is really good. Here is an open source app that is a must have when working with core data although it could use an easier way to interact with the on device Core Data files.

    https://github.com/yepher/CoreDataUtility


  • B

    BB

    Author Reply

    #import
    #import “AppDelegate.h”
    int main(int argc, char *argv[])
    {
    @autoreleasepool {
    return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
    }
    } –Got a Thread 1:signal SIGABRT – program crashed after i tried to hit save. I have another core data tutorial with the same error new to programming….please any advice??


    • Richard

      RichardRichard

      Author Reply

      I’m getting the same error too. Can’t find what I seem to be doing wrong.


    • Nathaniel Lee

      Can you please post what it says in the console?


    • Jason

      JasonJason

      Author Reply

      Getting the same error as well. Felt like I learned quite a bit but stuck with this runtime error.


  • Jas

    JasJas

    Author Reply

    If i chose a tabbed application and manually added the core framework, will the following code still work to obtain the managed context?

    @implementation DeviceViewController

    – (NSManagedObjectContext *)managedObjectContext {

    NSManagedObjectContext *context = nil;

    id delegate = [[UIApplication sharedApplication] delegate];

    if ([delegate performSelector:@selector(managedObjectContext)]) {

    context = [delegate managedObjectContext];

    }

    return context;

    }


  • Visitor

    VisitorVisitor

    Author Reply

    In, DeviceViewController.m, method:

    – (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPathNo visible @interface for ‘UITableView’ declares the selector

    ‘dequeueReusableCellWithIdentifier:forIndexPath:’

    Why it is giving me an ARC issue?


  • Pakap84

    Pakap84Pakap84

    Author Reply

    Great tutorial but I’ve a big problem. At the end, when I want to run my application (i’ve a dark screen…). Nothing is display and there are no errors in Xcode…
    I don’t understand why…
    Thx


    • VvV

      VvVVvV

      Author Reply

      I face the same issue. Did you figure out the problem.
      Any help appreciated.

      Thanks.


      • RLG02

        RLG02RLG02

        Author Reply

        See comment above about this issue– you may need to add the storyboard to your project. Or you may also need to comment out (or remove) the window creation and display code in AppDelegate.m. This is explained in the original instructions above.


    • jagveer Rana

      i have same problem ,, any body can help me??


  • Pakap84

    Pakap84Pakap84

    Author Reply

    Great tutorial but, when I use the Iphone simulator, i have a dark screen (nothing displayed). For xcode, there is no errors…


    • iamxyt

      iamxytiamxyt

      Author Reply

      Setting “Main storyboard file base name” information in the MyStore-info.plist file, which tells the Xcode which storyboard you are using,


  • scud

    scudscud

    Author Reply

    I’m getting a SIGABRT error when I try to build at:
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

    in the DeviceViewController.m file. Can anyone help?


  • jadacoast

    jadacoastjadacoast

    Author Reply

    Hi guys, I’m getting the following issue however no errors are reported in the code and it says ‘Build Succeeded’ after I go to run it. Could anyone please help?

    {@autoreleasepool {

    return UIApplicationMain(argc, argv, nil, NSStringFromClass([myStoreAppDelegate class

    ]));

    }
    }


    • Nathaniel Lee

      You still there?


    • wahiba

      wahibawahiba

      Author Reply

      you have to delete a Breakpoint in your code


      • ish3lan

        ish3lanish3lan

        Author Reply

        in DeviceDetailViewController:

        add .text after calling uitextfields :

        [newDevice setValue:self.nameTextField.text forKey:@”name”];

        [newDevice setValue:self.versionTextField.text forKey:@”version”];

        [newDevice setValue:self.companyTextField.text forKey:@”company”];

        as we should give a NSString to be saved not a UITextField

        Hope that will help

        🙂


  • steven

    stevensteven

    Author Reply

    Such a great tutorial! But the problem I am struggling with is when I try to add a fourth text field for a device, there is bugs. Is there some I need to notice when I add text fields?


  • Radoslav

    RadoslavRadoslav

    Author Reply

    This tutorial was very helpful.Thanks.
    Just a question: Is it possible create more complicated queries e.g take devices with version more than 5.1, and how?


  • k0e3

    k0e3k0e3

    Author Reply

    Once done, do the same steps to create a new class named DeviceDetailViewControllerUIViewController. Again, go to Storyboard and set the custom class of the detail view controller as the “DeviceDetailViewController”.

    This part is a little confusing. You mean a new class named DeviceDetailViewController that’s a subclass of UIViewController right?


  • Cristiano72

    i have this problem


    • aradddd

      araddddaradddd

      Author Reply

      I have the same problem, please help us


  • Robert

    RobertRobert

    Author Reply

    mistake?

    DeviceDetailViewControllerUIViewController. Again, go to Storyboard and set the custom class of the detail view controller as the “DeviceDetailViewController”.

    should read?

    DeviceDetailViewController. Make it as a subclass of UITableViewController. Again, go to Storyboard and set the custom class of the detail view controller as the “DeviceDetailViewController”.


  • Darkmouse

    DarkmouseDarkmouse

    Author Reply

    Thank you for your tutorials and for your work, they are very usefull.
    Thank you very much¡¡


  • Krishna

    KrishnaKrishna

    Author Reply

    Nice tutorial. Got it at the first time. Thanks for clearing the fact that the core data is a different that other Databases like MySQL or SQL server. I was confused with it all the time.


  • Ashish Porecha

    Under Persistent Store Coordinator is a line:

    Forget about it you don’t understand what it is.

    WTF?!?! HAHAHAHAHAHA!!!


  • Lovevapour

    LovevapourLovevapour

    Author Reply

    Great tutorial!! thks! 😀


  • John Kealy

    John KealyJohn Kealy

    Author Reply

    Great tutorials! For some reason though when I click “Add” it does not fire up the modal… Any ideas?


  • jacob banks

    When i run it it is saying Application windows are expected to have a root view controller at the end of launch. and it is not showing my tableview just a white screen


    • jacob banks

      can anyone help with that?


    • RaviKumar Yaganti

      you have to remove the default code in the didfinishlaunchingwithoption in appdelegate.m


  • kkk

    kkkkkk

    Author Reply

    please help me. i have attributes winnumber Set the type as Integer32. Where I corrected in this project.? thank you.


  • Canyon Grand

    can you help me ? Add Searchbar in tableview with Coredata .


  • Guest

    GuestGuest

    Author Reply

    Your Source code of the CoreData is not working in my devices!!!


  • sankar ram

    sankar ramsankar ram

    Author Reply

    Please help me in this problem!! I am getting error in this line in DeviceViewController.m file

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];


  • nuclear

    nuclearnuclear

    Author Reply

    This tutorial may have some issue, it is not working for most people from the comments


  • planbmn

    planbmnplanbmn

    Author Reply

    Same issue as jadacoast. Applied other suggestions but still getting NSException. Should this tutorial still work for iOS SDK 7.0?


  • pradeep

    pradeeppradeep

    Author Reply

    Could somebody help me ? I’m getting the below error after hitting ‘save’ button. I’m using xcode 5

    2014-02-26 00:00:27.061 MyStore[1916:70b] *** Terminating app due to uncaught exception ‘NSInvalidArgumentException’, reason: ‘Unacceptable type of value for attribute: property = “name”; desired type = NSString; given type = UITextField; value = <UITextField: 0x8b53b20; frame = (20 88; 280 30); text = 'abc'; clipsToBounds = YES; opaque = NO; autoresize = RM+BM; gestureRecognizers = ; layer = >.’

    *** First throw call stack:

    (

    0 CoreFoundation 0x01a9f5e4 __exceptionPreprocess + 180

    1 libobjc.A.dylib 0x018228b6 objc_exception_throw + 44

    2 CoreData 0x0029631e _PFManagedObject_coerceValueForKeyWithDescription + 3614

    3 CoreData 0x00263c49 _sharedIMPL_setvfk_core + 185

    4 CoreData 0x002954a6 -[NSManagedObject(_PFDynamicAccessorsAndPropertySupport) _setGenericValue:forKey:withIndex:flags:] + 54

    5 CoreData 0x00283b99 _PF_Handler_Public_SetProperty + 105

    6 CoreData 0x00283b23 -[NSManagedObject setValue:forKey:] + 163

    7 MyStore 0x000040e2 -[MSDeviceDetailViewController save:] + 226

    8 libobjc.A.dylib 0x01834874 -[NSObject performSelector:withObject:withObject:] + 77

    9 UIKit 0x005920c2 -[UIApplication sendAction:to:from:forEvent:] + 108

    10 UIKit 0x00866c9b -[UIBarButtonItem(UIInternal) _sendAction:withEvent:] + 139

    11 libobjc.A.dylib 0x01834874 -[NSObject performSelector:withObject:withObject:] + 77

    12 UIKit 0x005920c2 -[UIApplication sendAction:to:from:forEvent:] + 108

    13 UIKit 0x0059204e -[UIApplication sendAction:toTarget:fromSender:forEvent:] + 61

    14 UIKit 0x0068a0c1 -[UIControl sendAction:to:forEvent:] + 66

    15 UIKit 0x0068a484 -[UIControl _sendActionsForEvents:withEvent:] + 577

    16 UIKit 0x00689733 -[UIControl touchesEnded:withEvent:] + 641

    17 UIKit 0x005cf51d -[UIWindow _sendTouchesForEvent:] + 852

    18 UIKit 0x005d0184 -[UIWindow sendEvent:] + 1232

    19 UIKit 0x005a3e86 -[UIApplication sendEvent:] + 242

    20 UIKit 0x0058e18f _UIApplicationHandleEventQueue + 11421

    21 CoreFoundation 0x01a2883f __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 15

    22 CoreFoundation 0x01a281cb __CFRunLoopDoSources0 + 235

    23 CoreFoundation 0x01a4529e __CFRunLoopRun + 910

    24 CoreFoundation 0x01a44ac3 CFRunLoopRunSpecific + 467

    25 CoreFoundation 0x01a448db CFRunLoopRunInMode + 123

    26 GraphicsServices 0x039009e2 GSEventRunModal + 192

    27 GraphicsServices 0x03900809 GSEventRun + 104

    28 UIKit 0x00590d3b UIApplicationMain + 1225

    29 MyStore 0x000045ad main + 141

    30 libdyld.dylib 0x020dd70d start + 1

    )

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


    • pradeep

      pradeeppradeep

      Author Reply

      It’s my mistake. I found what i had done wrong. I forgot to add “.text” in [newDevice setValue:self.nameTextField.text forKey:@”name”]; It is solved now after adding “.text”. Very nice and easy tutorial to start with core data. Thanks for the tutorial


  • Marco Boldetti

    Hi guys, i have a question? like implementing core data in a existing project?


  • Rob

    RobRob

    Author Reply

    If you’re running into a runtime exception when you click the + (add) button, you probably didn’t set the subclass for DeviceDetailViewController properly. It should be UIViewController not UITableViewController. The instructions above do not make this clear.


  • dodets

    dodetsdodets

    Author Reply

    i have following error after click ‘+’ button :

    Terminating app due to uncaught exception ‘NSInternalInconsistencyException’, reason: ‘-[UITableViewController loadView] loaded the “nXf-mE-RFU-view-uFh-s5-Woc” nib but didn’t get a UITableView.

    what should i do? anyone can help?
    thanks


    • kamneed

      kamneedkamneed

      Author Reply

      See my answer to sajinseethi


      • Priyal Jain

        It’s really handy for other if you could repost your solution because searching for sajinseethiis really a cumbersome task.


        • kamneed

          kamneedkamneed

          Author Reply

          Delete three not needed methods in DeviceDetailViewController.m:
          – (id)initWithStyle:(UITableViewStyle)style
          – (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
          and
          – (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

          and see Rob’s answer regarding UIViewController not UITableViewController.


  • sajinseethi

    I’m getting this error !! Whats this about ? Thanks…

    2014-05-29 18:12:48.015 MyStore[7227:60b] *** Terminating app due to uncaught exception ‘NSInternalInconsistencyException’, reason: ‘-[UITableViewController loadView] loaded the “uwL-Dg-77k-view-cRO-bK-ZrR” nib but didn’t get a UITableView.’

    *** First throw call stack:


    • kamneed

      kamneedkamneed

      Author Reply

      Delete three not needed methods in DeviceDetailViewController.m:
      – (id)initWithStyle:(UITableViewStyle)style
      – (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
      and
      – (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

      and see Rob’s answer regarding UIViewController not UITableViewController.


  • Kiran

    KiranKiran

    Author Reply

    Nice tutorial


  • Mustafa Kuru

    It works, thanks


  • Czarek

    CzarekCzarek

    Author Reply

    Add button does not trigger seque, anyone know how to fix that?


  • www.imtikon.com

    this is a good one as a tutorial


  • RaviKumar Yaganti

    view is not dismissing…….

    – (IBAction)cancel:(id)sender {

    [self dismissViewControllerAnimated:YES completion:NULL];

    }


  • Raghunath

    RaghunathRaghunath

    Author Reply

    I am not able to create NSManagedObject instance (*newDevices).It doesn’t allow me to write NSManagedObject.In Screenshot ,Just i have Copied.It allows only NSManagedObjectContext and NSManagedObjectModel…. Whats the Problem??


    • Raghunath

      RaghunathRaghunath

      Author Reply

      provide me solution…….


      • Guest

        GuestGuest

        Author Reply

        Try importing CoreData at the top.
        #import


  • Napster

    NapsterNapster

    Author Reply

    Hi The DeviceDetail Page crashes as soon as I enter the input in textboxes. Any help will be much appreciated?


  • kuldeep tanwar

    how can you miss
    #import

    i’ve benn banging my head around for weeks 😀


  • kuldeep tanwar

    how can you miss
    @import CoreData;


  • Hishou

    HishouHishou

    Author Reply

    Would it be possible to update the Core Data series of tutorials for Swift 3? thanks!


  • joanpozo

    joanpozojoanpozo

    Author Reply

    my friend was searching for LITHO TOPS Form 3285 earlier this week and encountered a website with lots of form templates . If you are looking for LITHO TOPS Form 3285 too , here’s a https://goo.gl/xEVYnU.


  • Alexandru

    AlexandruAlexandru

    Author Reply

    I already worked with CoreData before but some time passed since then. And it looks like some things changed since then.

    I included CoreData from the beginning, but I couldn’t access the ManagedObjectContext from AppDelegate, like it is explained inside the tutorial. So this didn’t work anymore. Looks like Apple changed something since than, and moved the ManagedObjectContext to the PersistentContainer.

    – (NSManagedObjectContext *)managedObjecteContext{

    NSManagedObjectContext *context = nil;
    id delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    if( [delegate performSelector:@selector(persistentContainer)] ){

    context = [[delegate persistentContainer] viewContext];
    }
    return context;
    }

    Like in Swift, try to use the (AppDelegate *) class specification. The swift pendant is the same

    let context = (UIApplication.shared().delegate as! AppDelegate


    • Genie Music

      You saved my life, it works like a charm 😀


      • Alexandru

        AlexandruAlexandru

        Author Reply

        Glad to hear it helped!
        It took me some hours to find the problem xD


  • Kashyap Bhatt

    Hello,

    I am getting this error:

    Terminating app due to uncaught exception ‘NSInvalidArgumentException’, reason: ‘+entityForName: nil is not a legal NSManagedObjectContext parameter searching for entity name ‘Device”


  • manoj shivhare

    hey guys, i am facing problem..
    Terminating app due to uncaught exception ‘NSInvalidArgumentException’, reason: ‘-[AppDelegate managedObjectContext]:


Shares