RSS

Core Data Basics Part 2 – Core Data Views

12 Feb


Introduction

In this Part 2 of Core Data Basics I’ll explain:

  • Enabling Core Data in AppDelegate
  • Enabling a View for Core Data
  • Creating a Data Model
  • Linking Data to a View
  • Inserting Data via a View

Prerequisites

We follow on from Part 1 where we’ve already created a simple Storyboard app with delegation.  Download the project from the end of Part 1 then extract and open it with Xcode.

Boring Theory

Before we continue you need to know some things:

  • The persistentStoreCoordinator is the middleman between everything in Core Data.
  • The managedObjectModel is like a database schema.
  • The managedObjectContext is where data objects are managed.  When you save data you will save to the Managed Object Context.  At some point later on the ‘Persistent Store Coordinator’ writes the changes to the actual database file.

Enabling Core Data in the AppDelegate

The simplest way I found to add Core Data to an application was to copy the app delegate out of a new Xcode project created from a template with Core Data already in it.  Click File > New > New Project… to create a new Master-Detail Application project:

Set the Product Name to Template then ensure Use Core Data is ticked:

All we need from the Template project is all the code in AppDelegate.h and AppDelegate.m.  Copy it into the files of the same names in the Staff Manager project.  You can now close and delete the Template project.

AppDelegate.m will now contain references to a MasterViewController that doesn’t exist. Search AppDelegate.m and replace text MasterViewController with RolesTVC anywhere you find it.

If in the future the initial view controller is not RolesTVC you will need to replace RolesTVC with the name of the its view controller. AppDelegate should usually pass a Managed Object Context to the initial view controller. That view controller should then pass the Managed Object Context off to other views if required (like a baton). Read more about that here.

For the sake of completeness replace the text Template.sqlite with StaffManager.sqlite in AppDelegate.m

Enabling a View for Core Data

I learned the most about Core Data from watching a free iTunes-U iOS lecture set released by Stanford University.  Those lectures are brilliant and my hat goes off to Paul Hegarty who gives them. The reason I bring this up is that we will be leveraging a UITableViewController subclass provided during that lecture which is called CoreDataTableViewController.  You can download it from here or the Stanford site.

Once you have downloaded and extracted CoreDataTableViewController.zip drag the .h and .m files in to your project (copy). The CoreDataTableViewController class has good commenting in case you want to find out more about what it does (fetching!). I’m more interested in showing you how to use it.

CoreDataTableViewController inherits from UITableViewController and adds some functionality that RolesTVC needs. To inherit from CoreDataTableViewController instead of UITableViewController add to RolesTVC.h as follows, replacing the existing @interface declaration line:

#import "CoreDataTableViewController.h" // so we can fetch
@interface RolesTVC : CoreDataTableViewController <AddRoleTVCDelegate>
@property (strong, nonatomic) NSFetchedResultsController *fetchedResultsController;
@property (strong, nonatomic) NSManagedObjectContext *managedObjectContext;

More Boring Theory

Before we create a Data Model, you need to know some more things:

  • A Data Model is like a Database Schema (You need it to set up your managedObjectModel)
  • An Entity is like a Database Schema Table
  • An Attribute is like a Database Table Record
  • An Entity can have relationships with other Entities like Tables can have relationships to other Tables in a Database Schema
  • To work with an Entity within your code you need to create a subclass of NSManagedObject

You don’t have to understand that stuff just yet, you’ll start to see it in action soon.

Creating a Data Model

A Data Model is used to logically map out your apps data and data relationships. We will be creating a Data Model that is used in an app that manages what Roles people are in at work.  I will discuss the relationships between roles and staff (people) in Part 3 of this tutorial series.  For now, let’s set up a Data Model to handle a list of Roles.

Create an iOS Data Model by clicking File > New > New File then selecting Data Model:

Save the file name as Model.

Once you have your shiny new Model.xcdatamodeld file select AppDelegate.m, search for the word Template, then replace it with Model.

To create your first Entity select Model.xcdatamodeld then click the giant Add Entity button. Set the name of the new Entity to Role:

Click the plus sign to add a new Attribute. Call the Attribute name and set the Type to String:

Linking Data to a View

To use this new Data Model within code we need to create a NSManagedObject subclass for Role.  Select the Role entity, click Editor > Create NSManagedObject Subclass… then click Create.  You should now have two files Role.h and Role.m which represent your Role entity.  Any time you change the Role entity in the Data Model don’t forget to regenerate these files again.

Add the following to the top of both RolesTVC.h and AddRoleTVC.h:

#import "Role.h"

Add the following to the top of RolesTVC.m (beneath @implementation RolesTVC):

@synthesize fetchedResultsController = __fetchedResultsController;
@synthesize managedObjectContext = __managedObjectContext;
 
- (void)setupFetchedResultsController
{
    // 1 - Decide what Entity you want
    NSString *entityName = @"Role"; // Put your entity name here
    NSLog(@"Setting up a Fetched Results Controller for the Entity named %@", entityName);
 
    // 2 - Request that Entity
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:entityName];
 
    // 3 - Filter it if you want
    //request.predicate = [NSPredicate predicateWithFormat:@"Role.name = Blah"];
 
    // 4 - Sort it if you want
    request.sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"name"
                                                                                     ascending:YES
                                                                                      selector:@selector(localizedCaseInsensitiveCompare:)]];
    // 5 - Fetch it
    self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request
                                                                        managedObjectContext:self.managedObjectContext
                                                                          sectionNameKeyPath:nil
                                                                                   cacheName:nil];
    [self performFetch];
}
 
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self setupFetchedResultsController];
}

Once that’s all done you can freely use self.fetchedResultsController to bring data to the table view cells. In the cellForRowAtIndexPath method of RolesTVC.m add the following where it says ‘configure the cell’:

// Configure the cell...
    Role *role = [self.fetchedResultsController objectAtIndexPath:indexPath];
    cell.textLabel.text = role.name;

You have now done everything you need to do in order to bring back the contents of the Role entity to the Roles Table View.  The only problem is there’s no data to display!

Inserting Data via a View

Select MainStoryboard.storyboard then create a linked property in AddRoleTVC from the Text Field by doing the following:

  1. Change to Assistant Editor
  2. Select the Text Field on the Add Role View Controler
  3. Hold down Control while you drag a line to connect it to a new property:

Call the new property roleNameTextField then click Connect:

Xcode will now have created the view connected roleNameTextField property and the relevant synthesize in AddRoleTVC.m.

AddRoleTVC needs somewhere to hold the Managed Context passed from RolesTVC. Add the following property to AddRoleTVC.h:

@property (strong, nonatomic) NSManagedObjectContext *managedObjectContext;

Add this near the top of AddRoleTVC.m:

@synthesize managedObjectContext = __managedObjectContext;

Head back to RolesTVC.m and add the following in the prepareForSegue method (just after addRoleTVC.delegate = self;).  This is where the Managed Object Context gets passed along like a baton:

addRoleTVC.managedObjectContext = self.managedObjectContext;

Change the save method in AddRoleTVC.m as follows:

- (IBAction)save:(id)sender
{
    NSLog(@"Telling the AddRoleTVC Delegate that Save was tapped on the AddRoleTVC");
 
    Role *role = [NSEntityDescription insertNewObjectForEntityForName:@"Role"
                                               inManagedObjectContext:self.managedObjectContext];
 
    role.name = roleNameTextField.text;
 
    [self.managedObjectContext save:nil];  // write to database
 
    [self.delegate theSaveButtonOnTheAddRoleTVCWasTapped:self];
}

If you run the app now you should be writing successfully to the Managed Context … and inevitably the database:

Not convinced?  Lets take a look at the automagic SQL that’s going on behind the scenes by enabling debug.  Click Staff Manager > Edit Scheme…:

Click the + sign in the Arguments Passed On Launch section.  Add -com.apple.CoreData.SQLDebug 1 as an argument:

Re-run the app and you should see some SQL wizardry:

That’s it for now, stay tuned for Part 3 where I expand on the Data Model by introducing editing, deleting and relationships.

Here’s the source code so far

If you liked this tutorial or found something wrong with it please let me know!

If you want to support my work and have an iPad please consider purchasing iSoccer *wink*

-Tim

Go to Part 3 or the Tutorials Index


Be Sociable, Share!
     

    About Tim Roadley

    I'm a senior analytics software consultant at eMite Pty Ltd primarily focused on delivering business intelligence dashboards, currently for one of Australia’s major banks. I'm also working on a revamped version of eMite's iOS App for release under iOS 7. Prior to eMite, I was Infrastructure Manager at Cuscal Pty Ltd where I was heavily involved in designing and implementing a payments switch that drives 1300+ ATM’s Australia wide. I have several apps on the App Store, including Teamwork, iSoccer and now Grocery Dude and Grocery Cloud. In my down time I enjoy spending time with my wonderful wife Tracey and two lovely children Tyler and Taliah.
    120 Comments

    Posted by on February 12, 2012 in iOS Tutorials

     

    120 Responses to Core Data Basics Part 2 – Core Data Views

    1. Michael

      August 22, 2012 at 12:06 am

      Hello, Great Tutorial has been excellent help.

      I’ve a question however well require an explanation.

      Its similar to previous posts i know, my application consists of a UIViewController -> UINavigationController -> UITableController basically same as tutorial however with a view controller in front of it all. I’ve been trying for a while to get it to work. I was continually getting a non-nil fetch request, until i added this into my UITableView

      AppDelegate *delegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
      self.managedObjectContext = delegate.managedObjectContext;

      I really just want to explanation of what this has done and if its appropriate?

      Thanks

      Michael

       
    2. bruno

      August 28, 2012 at 9:22 pm

      tim u don’t have the same version of the tutorial without the coredatatableviewcontroller class? I don’t wanna use it for fetch core data information. Thanks a lot

       
    3. Sallywellie

      August 31, 2012 at 3:22 pm

      Hey guys, I am having the same problem too as well.
      ERROR: Cannot create an NSPersistentStoreCoordinator with a nil model’

      However I found my solution in stackoverflow, and funny as it seems this is what i had to do to fix it..

      Seems like this was the part that wasn’t working for me :

      - (NSManagedObjectModel *)managedObjectModel
      {
      if (__managedObjectModel != nil)
      {
      return __managedObjectModel;
      }
      NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@”Model” withExtension:@”momd”];
      __managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
      return __managedObjectModel;
      }

      So i changed to it ..

      - (NSManagedObjectModel *)managedObjectModel {
      if (__managedObjectModel != nil) {
      return __managedObjectModel;
      }
      __managedObjectModel = [NSManagedObjectModel mergedModelFromBundles:nil];
      return __managedObjectModel;
      }

      and everything else was working too .. Not too sure why though :(

       
    4. jcubero

      September 8, 2012 at 12:03 pm

      Hi,
      I think your tutorials are really great, I’m a newbie in XCode and iOS programming, I’m following your tutorial in order to implement data storage in an small application.
      I followed everything and I’m getting the following error when compiling, I’m not missing the reference to CoreData.framework.

      Undefined symbols for architecture i386:
      “_OBJC_CLASS_$_CoreDataTableViewController”, referenced from:
      _OBJC_CLASS_$_RolesTVC in RolesTVC.o
      “_OBJC_METACLASS_$_CoreDataTableViewController”, referenced from:
      _OBJC_METACLASS_$_RolesTVC in RolesTVC.o
      ld: symbol(s) not found for architecture i386
      clang: error: linker command failed with exit code 1 (use -v to see invocation)

      If you can help me I would really appreciate it.

       
      • Tim Roadley

        September 8, 2012 at 6:23 pm

        Hmm is that a Mac or iOS project? Seems a bit odd. I assume you linked to the core data framework?

        Perhaps post a question on stackoverflow, they’re pretty good with stuff like this.

        Does the sample project work for you?

         
        • jcubero

          September 9, 2012 at 9:36 am

          Thank you Tim I just solved the issue with Cyber suggestion, it is an iOs project. I followed your instructions and I haven’t downloaded the sample project.

           
      • Cyber

        September 8, 2012 at 11:12 pm

        Hi

        I also had the same problem, found the answer on the stackoverflow.
        You need to set the target of the CoreDataTableViewController.m to the correct file. Select the .m file and in the property inspector tick the project target file.

         
        • jcubero

          September 9, 2012 at 9:33 am

          it worked nicely, thank you

           
        • Chen Lala

          October 21, 2012 at 5:57 pm

          Can you show how to do [set the target of the CoreDataTableViewController.m to the correct file. Select the .m file and in the property inspector tick the project target file.]?
          thanks ^^

           
    5. Matt

      September 15, 2012 at 12:24 am

      Hey I tried changing the properties like you said in the property inspector for both the AppDelegate.m and CoreDataTableBiewController.m and even more errors came up… this is what I have now

      Undefined symbols for architecture i386:
      “_NSSQLiteStoreType”, referenced from:
      -[AppDelegate persistentStoreCoordinator] in AppDelegate.o
      “_OBJC_CLASS_$_NSEntityDescription”, referenced from:
      objc-class-ref in AddRoleTVC.o
      “_OBJC_CLASS_$_NSFetchRequest”, referenced from:
      objc-class-ref in RolesTVC.o
      “_OBJC_CLASS_$_NSFetchedResultsController”, referenced from:
      objc-class-ref in RolesTVC.o
      “_OBJC_CLASS_$_NSManagedObject”, referenced from:
      _OBJC_CLASS_$_Role in Role.o
      “_OBJC_CLASS_$_NSManagedObjectContext”, referenced from:
      objc-class-ref in AppDelegate.o
      “_OBJC_CLASS_$_NSManagedObjectModel”, referenced from:
      objc-class-ref in AppDelegate.o
      “_OBJC_CLASS_$_NSPersistentStoreCoordinator”, referenced from:
      objc-class-ref in AppDelegate.o
      “_OBJC_METACLASS_$_NSManagedObject”, referenced from:
      _OBJC_METACLASS_$_Role in Role.o
      ld: symbol(s) not found for architecture i386
      clang: error: linker command failed with exit code 1 (use -v to see invocation)

      any thoughts?

      Thanks Matt

       
      • Michiel Roos

        September 26, 2012 at 3:31 pm

        When you add files to the project, make sure you add the files to your project targets by checking the box next to your project’s target in the dialog window!

        Kind regards,

        Michiel

         
    6. Shohrab

      October 9, 2012 at 8:04 pm

      Excellent Writing..butI think it will be little-bit hard to grasp for new learner.Why you were not trying with simple UIViewController rather than use UITableViewController.But good job and learn lots of new things from you.Thanks buddy.

       
    7. BreeGeek

      October 11, 2012 at 8:18 pm

      Hi Awesome tutorial !

      But I have a bug saying, Terminating app due to uncaught exception ‘NSInvalidArgumentException’, reason: ‘An instance of NSFetchedResultsController requires a non-nil fetchRequest and managedObjectContext’

      do you have a lead ?

       
      • Marco

        November 15, 2012 at 9:12 am

        BreeGeek, I have the same issue. If you figure this out, please post it.

         
        • mario

          November 21, 2012 at 6:47 am

          same problem here. anyone solve this?

           
      • Sandip

        December 4, 2012 at 3:50 am

        this might help.. had similar error on mine as well.. solution was posted by Sallyweli..ie

        Sallywellie
        August 31, 2012 at 3:22 pm
        Hey guys, I am having the same problem too as well.
        ERROR: Cannot create an NSPersistentStoreCoordinator with a nil model’

        However I found my solution in stackoverflow, and funny as it seems this is what i had to do to fix it..

        Seems like this was the part that wasn’t working for me :

        - (NSManagedObjectModel *)managedObjectModel
        {
        if (__managedObjectModel != nil)
        {
        return __managedObjectModel;
        }
        NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@”Model” withExtension:@”momd”];
        __managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
        return __managedObjectModel;
        }

        So i changed to it ..

        - (NSManagedObjectModel *)managedObjectModel {
        if (__managedObjectModel != nil) {
        return __managedObjectModel;
        }
        __managedObjectModel = [NSManagedObjectModel mergedModelFromBundles:nil];
        return __managedObjectModel;
        }

        and everything else was working too .. Not too sure why though :(

         
      • kevin

        December 29, 2012 at 11:29 am

        Hi BreeGeek,

        I had this same problem. It stems from the managedObjectContext. Take a look at the source code from the project. In the AppDelegate.m file under applicationDidFinishLaunchingWithOptions. You will have to pass on the managedObjectContext like so:

        RolesTVC *controller = (RolesTVC *)navigationController.topViewController;
        controller.managedObjectContext = self.managedObjectContext;

        That should fix your problem.

         
    8. ralph

      November 10, 2012 at 7:06 pm

      6 errors and a pile of confusion. AddRoleTVC.h is a war zone of errors. What happened here – am I using the working version of xcode or something???

       
    9. Marco

      November 15, 2012 at 3:55 am

      Hi Tim,

      first, thanks a lot for the tutorials. I’m doing it for the second time.

      Actually, that seems to be the problem. This time, I’m doing straight using iPad as a target (skipping the iPhone) part.

      I’m having trouble with the following code in my AppDelegate.m.

      UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
      UINavigationController *navigationController = [splitViewController.viewControllers lastObject];
      splitViewController.delegate = (id)navigationController.topViewController; // Error happens here

      UINavigationController *masterNavigationController = splitViewController.viewControllers[0];
      L4ProvinceTableViewController *controller = (L4ProvinceTableViewController *)masterNavigationController.topViewController;
      controller.managedObjectContext = self.managedObjectContext;

      I did change the classes using my own naming convention. What it has been very hard for to understand (not just in your tutorial0 is how to access the views.

      I’m sure you’re very busy and I once again, thank you for your work.

      Any help would be greatly appreciated.

      Thanks in advance

      Marco

       
    10. Esteban Gambino

      November 15, 2012 at 10:55 am

      Greets All – Tim, what a nice tutorial. Thanks for enabling an old crippled man the opportunity to learn something new and exciting. After finishing part 2 of this tutorial, my app is terminating at the ‘press save’ area, with an +entityForName: nil is not a legal NSManagedObjectContext parameter searching for entity name ‘Role’. This must be a typo or overlook on my part.
      I am a 52 y/o happily married male quadriplegic, severed my spinal chord in ’88, attempting to sleep and operate a motor vehicle at the same time, doesn’t work for long. Nevertheless, do you know which file is causing my issue? Thanks in advance.

      Steven

       
    11. Anthony

      November 22, 2012 at 7:37 pm

      Great tutorial. But I need help.
      I used your steps to intergrade CoreData into my existing project. My first controller is a Tab Bar Controller. You stated in your tutorial to replace the RolesTVC with the name of my view controller in the AppDelegate. But since I am using a Tab Bar Controller as my first view I don’t know how to do this. Help would be appreciated. Thanks in advance.
      Anthony

       
      • Anthony

        November 22, 2012 at 8:05 pm

        Found the answer.
        In any given ViewController that you want to have access to the Core Data, put this in viewDidLoad:
        id appDelegate = (id)[[UIApplication sharedApplication] delegate];
        self.managedObjectContext = [appDelegate managedObjectContext];

        I also removed all the statements in the AppDelegate: didFinishLaunchingWithOptions, except for return YES;

        I just hope this will not interfere with the remaining of tutorials.

        Anthony

         
    12. El Tea

      November 29, 2012 at 1:48 pm

      His use of performFetch has an issue – it needs to be:

      NSError *error;
      [self.fetchedResultsController performFetch:&error];

      I don’t know if this is a quick change he missed or a change in compilers…

       
    13. kevin

      December 29, 2012 at 11:36 am

      HI Tim,

      First off, thanks very much. Your tutorial on Core Data is very helpful. I think some issues are popping up that are probably due to new versions of Xcode more than your code. Downloading the source code for reference really helps.

      I do think that you should change one thing on this tutorial. Under Enabling Core you state this:

      “AppDelegate.m will now contain references to a MasterViewController that doesn’t exist. Search AppDelegate.m and replace text MasterViewController with RolesTVC anywhere you find it.”

      When I attempted this, all went incredible wrong. The master detail template does not use a storyboard and is set up very differently. Even your source code is different from the way Xcode sets this up. I am using Xcode 4.5.2.

      Again I am grateful for the work and will continue onto section 3 now.

      Kevin

       
      • jrr

        January 4, 2013 at 6:59 pm

        Kevin,Did you get your answer?

         
    14. jrr

      January 4, 2013 at 6:56 pm

      Problem is with managed object context: the property not found.
      How to slove this?

       
    15. jrr

      January 4, 2013 at 7:12 pm

      Thanks for this great tutorial for core data.I’m using Xcode 4.4.1 and while adding “RolesTVC” I’m using “objective c class” instand of “UIViewController subClass”.Becoz, This Xcode does not have the option to select “UIViewControllerSubClass”.I’m getting error “Managed object context propety not found”. Plaese suggest.

       
    16. jrr

      January 7, 2013 at 11:03 pm

      Just curious to know:
      If I’m commenting this its working fine:

      - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
      {
      #warning Potentially incomplete method implementation.
      // Return the number of sections.
      return 0;
      }

      - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
      {
      #warning Incomplete method implementation.
      // Return the number of rows in the section.

      return 0;
      }

      Otherwise, i’m not able to see the table cell in “Add Role”.Why is it so?Is it becoz, we have taken static table view cell? Please clarify??

       
      • Tim Roadley

        January 8, 2013 at 5:52 am

        Those methods are in the superclass (CoreDataTableView), so if you implement them in the subclass and get them to return 0, they will tell the tableview that there are 0 rows or sections in the table!

         
    17. pino3191

      February 12, 2013 at 1:46 am

      Hey!

      Thank you so much for your tutorial, it works very fine :)

      But I tried to use a TabBarController with a NavigationController and I have some errors in my AppDelegate.m, in de methods didFinishLaunchingWithOptions.

      Here is my code in this method:

      UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
      UINavigationController *navigationController = [splitViewController.viewControllers lastObject];
      splitViewController.delegate = (id)navigationController.topViewController;

      But as I have a TabBarController, I have to edit this method, but how ?

      If you want a screenshot of my storyboard, just ask me ;)

      Thank you so much!

       
      • pino3191

        February 12, 2013 at 1:48 am

        I forgot to put the error:

        2013-02-11 16:48:04.689 travail[4850:c07] *** Terminating app due to uncaught exception ‘NSInvalidArgumentException’, reason: ‘An instance of NSFetchedResultsController requires a non-nil fetchRequest and managedObjectContext’

        Thank you so much!

         
        • Darrell Nicholas

          March 18, 2013 at 3:25 am

          Here’s what I did to overcome this error…

          At the top of AppDelegat.m
          add…
          @synthesize window = _window;

          also I changed the following
          In RolesTVC.m in the

          - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath method

          make sure you leave off the indexPath:indexPath at the end of dequeReusableCellWith Identifier. Like so:

          UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

          the default add the indexPath part at the end.

          I changed those 2 things and the app compiled and functioned without error. This is the way he has it in the sample code. That’s how I found this.

           
    18. adrian

      February 12, 2013 at 1:53 am

      the error is telling you that you have not added the managed object to your split view controller. check out how tim is adding the managed objects in app delegate to both his view controllers. make sure you declare the managed object in your classes as well. a good lead would be to look at the sample project and see where adds the managed object and how. hope this helps you my friend

       
    19. pino3191

      February 12, 2013 at 5:57 pm

      Yeah! I Fixed it! Thank you adian :D

       
    20. mcbain

      February 21, 2013 at 1:40 am

      Hi,
      fantastic tutorial. It works great.

      But I still got one problem. My storyboard has one table view controller for the table with the core data stuff, that shows my stored data. Similar to the first one in the tutorial.
      After that i have a tableviewcontroller that leads to another tableviewcontroller. The first one contains categories and the values i need are in the other third one.

      Like 1 -> 2 -> 3, i want to store the data from 3 and show it in 1. 2 is just to select the category for 3.
      Obviously I have some issues with the segue to through these three tableviewcontrollers.

      Could you please give me some advice?

       
    21. abban

      February 21, 2013 at 4:58 am

      Have you noticed that when you delete a row the cells beneath pop up and hide the delete animation? Something to do with the table updating before the animation is finished maybe?

       
    22. abban

      February 21, 2013 at 6:07 am

      Ok I know whats going wrong, you just have a couple of errors in your code. There’s comments in the CoreDataTableViewController that say you shouldn’t ever have to call the performFetch method after you do it in the setupFetchedResultsController as the NSFetchedResultsController automatically handles that. You do need to set the delegate of the NSFetchedResultsController as your tableViewController though. Then to delete data you just:

      [code]
      [self.managedObjectContext deleteObject:object];
      [self.managedObjectContext save:nil];
      [/code]

      Don’t tell the table to delete at index path and don’t refetch the date. Zing, the animations are working. I haven’t tested yet but I assume this will also be the case for adding a new row too.

       
    23. abban

      February 21, 2013 at 6:11 am

      Actually just tested adding a new row. You also don’t have to bother informing the TableViewController that the save button was tapped, the NSFetchedResultsController sorts all that out for you too.

       
    24. Narciso

      May 28, 2013 at 9:36 am

      I getting this error: Terminating app due to uncaught exception ‘NSInvalidArgumentException’, reason: ‘-[UITableViewController setManagedObjectContext:]: unrecognized selector sent to instance 0x74804f0′. Any ideas ?

       
    25. icekomo

      October 24, 2013 at 2:33 pm

      I went through this tutorial and so far so good, I don’t have any errors at the end of part 2, but I am also not seeing any data when I test it.

      I didn’t see anywhere in the tutorial where we updated these methods.. do I have to in order to get this working?
      They are giving me warnings but not errors.

      #pragma mark – Table view data source

      - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
      {
      #warning Potentially incomplete method implementation.
      // Return the number of sections.
      return 0;
      }

      - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
      {
      #warning Incomplete method implementation.
      // Return the number of rows in the section.
      return 0;
      }

       
      • Tim Roadley

        October 26, 2013 at 9:26 am

        Hi Icekomo,

        Try deleting the numberOfSectionsInTableView and numberOfRowsInSection methods from RolesTVC.m. They’re implemented in CoreDataTableViewController.m and by over-riding them to return 0, you’ll see no data!

        Thanks!

        Tim

         
    26. Emily Priddy

      January 4, 2014 at 6:00 am

      Thanks so much for pointing me to Paul Hegarty’s videos! I read and re-read and watched and re-watched tons of books, articles, and videos trying to get a firmer grasp on MVC and just watching his first video made everything crystal clear immediately. You site and book have been such a valuable resource!!

       
    27. rob v

      January 31, 2014 at 5:25 pm

      v-e-r-y untidy
      it gets there eventually but some parts fail to communicate why it works, you’re far too rushed with it.
      some of your #import statements are either missing or in the wrong place

       
      • Tim Roadley

        January 31, 2014 at 5:38 pm

        Where are the #import statements missing or in the wrong place?

         

    Leave a Reply