iOS engineer who likes clean, simple designs and sans-serif.

Loading

CoreData [Example]

Below are my notes for getting CoreData to work on iOS 7.

  1. Create new project

    – Use Menu => New Project => iOS => Application => Empty Application.
    – Make sure to check “Use Core Data” and select which devices the app will work for.
    – Note: There is no storyboard file or root View Controller.

  2. Creating a Storyboard & Initial View Controller

    1. Remove code for didFinishLaunchingWithOptions so there are no conflicts when we set up a Storyboard

        - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
        {
            return YES;
        }
    2. Go to File => New File => iOS => User Interface => Storyboard

      – Choose storyboard layout size
      – Name your storyboard with layout size

    3. Click on Project Name => General => Deployment Info

      – Change main interface to be the storyboard you just created.
      – Verify Device, Device Orientation and Deployment Target

    4. Add your view controller to storyboard

      – Use Menu => Editor => Embed In => Navigation Controller to add in navigation

    5. Create class to manage your new view controller using

      – Menu => New => New File => iOS => Cocoa Touch => Objective C Class with proper subclass of view controller

    6. In storyboard, define the custom class for the view controller.

      – Define cells if appropriate

    7. Launch application to test.

    8. If applicable, in View Controller define property to hold NSMutableArray containing the data.
      – Use lazy instantiation to define the property
        - (NSMutableArray *)albums
        {
            if (!_albums) _albums = [[NSMutableArray alloc] init];
            return _albums;
        }
    9. Set up other optional/required methods for the view controller (ie: numberOfSectionsInTableViewController, numberOfRowsInSection)
  3. Set up xdatamodel

    – Select your .xcdatamodeld and click “Add entity”
    – Rename the new entity as singular object (not plural) and capitalized.
    – Define attributes and be sure to select a type.
    – Select Entity => Menu => Editor => Create NSManagedObject Subclass

  4. Set Up Storyboard buttons, actions and methods

  5. Import new object header file (Object.h)

  6. Save data to database

  7. Get access to NSManagedObjectContext and define the new object using insertNewObjectForEntityForName.

      - (Album *)albumWithName:(NSString *)name
      {
          id delegate = [[UIApplication sharedApplication] delegate];
          NSManagedObjectContext *context = [delegate managedObjectContext];

          Album *album = [NSEntityDescription insertNewObjectForEntityForName:@"Album" inManagedObjectContext:context];
          album.name = name;
          album.date = [NSDate date];

          NSError *error = nil;
          if (![context save:&error]) {
              // we have an error!
          }
          return album;
      }
  8. Add object to array property and update views

      [self.albums addObject:[self albumWithName:alertText]];
  9. Load data from Database

    – Retrieve all entities of a certain name

      NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Album"];

    – Sort in ascending date

      NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"date" ascending:YES];

    – Querying specific data

      NSPredicate *predicate = [NSPredicate predicateWithFormat:@"date >= %@", myDate];

    – Example:

      - (void)viewWillAppear:(BOOL)animated
      {
          [super viewWillAppear:animated];

          NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Album"];

          fetchRequest.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"date" ascending:YES]];

          NSError *error = nil;

          NSArray *fetchedAlbums = [[TWCoreDataHelper managedObjectContext] executeFetchRequest:fetchRequest error:&error];

          self.albums = [fetchedAlbums mutableCopy];
      l
          [self.tableView reloadData];
      }
  10. Refactoring with a CoreDataHelper Class

      LLCoreDataHelper.m

      +(NSManagedObjectContext *)managedObjectContext
      {
          NSManagedObjectContext *context = nil;

          id delegate = [[UIApplication sharedApplication] delegate];
          if ([delegate performSelector:@selector(managedObjectContext)]) {
              context = [delegate managedObjectContext];
          }

          return context;

      }

Leave a Comment