RSS

Core Data Basics Part 1 – Storyboards, Delegation

09 Feb


Introduction

Welcome to my tutorial set ‘Core Data Basics’. The aim of this set is to get you up and running with Core Data attached views as fast as possible.  If you’re new to objective-c programming you may wish to run through the iOS Newbie series first.  I’m going to provide raw essentials only so you don’t get too overwhelmed. I’m writing this tutorial set as a personal learning exercise because I found Core Data difficult to learn. I hope my ‘everything-you-need-and-nothing-you-don’t’ tutorial technique brings you up to speed quickly.

Prerequisites

To follow this tutorial I assume you know how to use Xcode at least in a basic sense. Again, try the iOS Newbie series if you’re lost.

Create a new iOS ‘Single View Application':

Call the project ‘Staff Manager’ and ensure the Device Family is iPhone:

Link to the Core Data Framework (click the + sign shown below to add it):

Creating a Storyboard

A Storyboard is a canvas where you can design your view based app. To view the storyboard simply select MainStoryboard.storyboard and you will see the default View. You can navigate between items in the View Controller Scene in a hierarchy on the left, which is useful when scenes become complicated.

Lets get started.  First delete the default view and the view controller so there is nothing in the scene. Now we can really start creating the app from scratch.

Drag a Table View Controller onto the canvas (via Utilities, Objects):

Select the Table View so it has a blue outline then click Editor > Embed In > Navigation Controller. Next rename the Table View Controller to Roles (via Attributes Inspector, Navigation Item, Title):

Select the Prototype Cell of the Table View Controller then set the Identifier of the Prototype Cell to Roles Cell (via Attributes Inspector, Table View Cell):

Drag a Bar Button Item onto the top right bar of the Table View Controller (via Utilities, Objects) then change the Bar Button Item identifier to ‘Add’ (via Attributes Inspector, Bar Button Item):

Drag a new Table View Controller onto the canvas (via Utilities, Objects) then re-align it so it is to the right of the Roles Table View Controller:

Create a Push Segue (Seg-way) from the Add button to the new Table View Controller by holding down the Control key and dragging from the Roles ‘Add’ button to the Add Roles Table View Controller:

Notice that the new Table View Controller is automatically embedded in a Navigation Controller. Rename the new Table View Controller to Add Role the same way we did for the Roles Table View Controller (via Attributes Inspector, Navigation Item, Title).  Run the app in the simulator to see what you have created so far with zero code!

Nice huh!  Now it’s time to further customise the Add Role view so it is ready for data entry.

Select the Add Role Table View then change the Content Type to Static Cells. Also change the Table View Style to Grouped then delete two of the Table View Cells.  Select the Table View Section then set the Header Name to Role Name.  After all that the Add Role Table View Controller should look like this:

If we ever want to enter data we need a Text Field so drag one on to the Add Role Table View Cell (via Utilities, Objects)

Change Text Field Border Style to invisible and resize it so that it fits nicely in the Table View Cell.  I find 260w 43h is a nice fit.  Set the Font to System 17 and Min Font Size to 17.

Finally, drag a Bar Button Item to the top right of the Add Role view and change it’s identifier to Save (via Attributes Inspector, Bar Button Item).

Run the app again and it should look like this when you tap the +

View Delegation

When you are in the Add Role view  you can already get back to Roles by pressing the automatically generated ‘Roles‘ button (top left).  If we want to go back to Roles when we click Save we need to configure the Roles view as a delegate of Add Roles view.

To do any customisation on a Table View Controller we need to subclass it. To make one click File > New > New File then create a New UIViewController subclass:

Ensure you select UITableViewController and call it RolesTVC:

Create another Table View Controller called AddRoleTVC in the same way so you now have two new UITableViewController subclasses:

Head back to MainStoryboard.storyboard again then select the Roles Table View Controller so it has a blue outline. Change the Class to RolesTVC (via Identity Inspector, Custom Class). Use the same technique for the Add Roles Table View Controller to set its custom class to AddRoleTVC:

Now that each Table View Controller has its own sub class we can start customising them. Our first order of business will be to edit AddRoleTVC to allow delegation by declaring a protocol AddRoleTVCDelegate. Change all the code in AddRoleTVC.h as follows:

#import 
 
@class AddRoleTVC;
@protocol AddRoleTVCDelegate
- (void)theSaveButtonOnTheAddRoleTVCWasTapped:(AddRoleTVC *)controller;
@end
 
@interface AddRoleTVC : UITableViewController
@property (nonatomic, weak) id <AddRoleTVCDelegate> delegate;
 
- (IBAction)save:(id)sender;
 
@end

Next change all the code in AddRoleTVC.m as follows:

#import "AddRoleTVC.h"
 
@implementation AddRoleTVC
@synthesize delegate;
 
- (void)viewDidUnload
{
    [super viewDidUnload];
}
- (IBAction)save:(id)sender
{
    NSLog(@"Telling the AddRoleTVC Delegate that Save was tapped on the AddRoleTVC");
    [self.delegate theSaveButtonOnTheAddRoleTVCWasTapped:self];
}
@end

Great! Now we can configure RolesTVC as a delegate of the AddRoleTVC.  To do that simply change all the code in RolesTVC.h as follows:

#import
#import "AddRoleTVC.h" // so this class can be a AddRoleTVCDelegate
 
@interface RolesTVC : UITableViewController <AddRoleTVCDelegate>
@end

Also change all the code in RolesTVC.m as follows:

#import "RolesTVC.h"
 
@implementation RolesTVC
 
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Roles Cell";
 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
 
    // Configure the cell...
 
    return cell;
}
 
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
	if ([segue.identifier isEqualToString:@"Add Role Segue"])
	{
        NSLog(@"Setting RolesTVC as a delegate of AddRolesTVC");
 
        AddRoleTVC *addRoleTVC = segue.destinationViewController;
        addRoleTVC.delegate = self;
	}
}
 
- (void)theSaveButtonOnTheAddRoleTVCWasTapped:(AddRoleTVC *)controller
{
    // do something here like refreshing the table or whatever
 
    // close the delegated view
    [controller.navigationController popViewControllerAnimated:YES];
}
 
@end

The delegation that we have just set up won’t work until we have set the identifier of the Segue on the storyboard. Set the name of the Segue to Add Role Segue (via Attributes Inspector, Storyboard Segue):

If you look in the prepareForSegue method found in RoleTVC.m you will notice that the AddRoleTVC delegation is set up in there. What that means is that any time the Add Role Segue is used that a delegate ‘anchor’ is created by prepareForSegue so we know how to get back to the Roles view once we’re finished with the AddRole view.  I hope that makes sense, it was a difficult concept for me to grasp originally however is very important for you to understand.

Lastly link the Save button to the save action by holding down control and dragging a line from the Save button down to the yellow circle on the Add Role Table View Controller.  You should get a pop-up on which you should select ‘save':

Run the app in the simulator, tap the + sign then tap Save.  Look in the log window of Xcode for the following entries.  You can should now see delegation occurring:

While it might seem all very boring now the ground work has been set to start working with Core Data.

Stay tuned for Part 2 which should get a whole lot more interesting!!

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 2 or visit 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.
    84 Comments

    Posted by on February 9, 2012 in iOS Tutorials

     

    84 Responses to Core Data Basics Part 1 – Storyboards, Delegation

    1. Dalton Hamilton

      October 16, 2013 at 8:52 am

      This tutorial looks great. Was following along until File->New->New File-> UIViewController. I’m on XCode5. I can go File->New->File and choose iOS/Cocoa Touch/ but under there I see no UIViewController.

       
      • Tim Roadley

        October 16, 2013 at 9:08 am

        Hello,

        Try this:

        Click File > New > File
        Click iOS > Cocoa Touch > Objective-C class
        Set Subclass of to UIViewController

        Hope that helps!

        Tim

         
    2. Sandy Lobban

      November 15, 2013 at 10:56 pm

      Hi There, Im using xcode 5.02. I may be missing something but is the sub classing only for navigational purpoes? Is it necessary to sub class the view controller classes? I understand it may be relevant to part 2, but you can get back to the roles screen form the save button by connecting the seque from the save button to the previous screen it seems. As I say, the sub classing is maybe something that is required for later. If you can let me know that would be great.

      cheers
      sandy

       
    3. Marcello

      December 9, 2013 at 9:11 pm

      Very good totorial!
      I’m interesting to know how we can put into a prototype cell a selector that push to a new view with only a textview and a button save and cancel. The user can write something and press the save button (or cancel to abort).
      The app will save the textview into a file.txt for ex.
      The last thing is: it’s possible create an array that contains the list of the files .txt written by the user? Maybe that are a lot of questions but in all tutorials tha I’ve seen I’ve found only 1 step of this procedure. So… how to save a file in a file.txt, or how to create a project with a tableview…, etc. The steps required for making 3 or 4 steps together are impossible to find. when we try to put all in one solution more that one tutorial the problems comes up.
      Thank very much for your help.

       
    4. Eric L. Pheterson

      December 19, 2013 at 6:09 pm

      Bro, you’re amazing. Thank you so much.

       
    5. Jon

      January 1, 2014 at 9:06 pm

      Sadly, I’m using XCode 5.02 and it all worked relatively fine until I got to delegation. There are a few typos (e.g. nothing being imported), but I assumed a UIKit.h. Then the class names were broken since I have a 3 letter prefix. I noticed that your sample code doesn’t match the tutorial either. A shame, since the approach you’ve taken is quite good. It seems that anyone not on an early version of XCode is a little out of the dark until a number of external tutorials catch up to XCode 5. Most of the good books are similarly not going to match XCode 5’s UI and it’s far from intuitive what the equivalents are.

      Thank you though, it looks like a good introduction.

       
    6. Jon

      January 2, 2014 at 10:10 am

      Thanks Tim – I got your mail, but your reply-to icloud email bounced. I will however, have a look at your book.

       
      • Jon

        January 2, 2014 at 8:32 pm

        OK – book now bought. Looks good.

         
    7. Eugene El

      April 10, 2014 at 9:53 pm

      Hello, Tim.
      Sorry, I didn’t find the proper place to ask my question, but I hope you’ll find some time to reply.
      In your book in listing 1.6 why did you use instance vars instead of properties?
      Does it matter? or it is just question of style?
      Thanks.

       
    8. daviddelmonte

      August 3, 2014 at 9:10 pm

      Tim, thanks for your tutorial efforts. I have implemented the core data searching/filtering, but it only finds words with the match in the first character. I must be missing something.. Should I jump to predicates instead? Can a predicate be used with an NSComparisonResult? Thanks again.

       

    Leave a Reply