Core Data by Tutorials iOS 8 and Swift Edition Aaron Douglas - Download the ebook and start exploring right away
Core Data by Tutorials iOS 8 and Swift Edition Aaron Douglas - Download the ebook and start exploring right away
Core Data in Swift Data Storage and Management for iOS and
OS X Marcus S. Zarra
https://ebookfinal.com/download/core-data-in-swift-data-storage-and-
management-for-ios-and-os-x-marcus-s-zarra/
https://ebookfinal.com/download/ios-8-swift-programming-cookbook-
solutions-examples-for-ios-apps-1st-edition-nahavandipoor/
https://ebookfinal.com/download/ios-5-by-tutorials-
volumes-1-and-2-2nd-edition-ray-wenderlich/
https://ebookfinal.com/download/core-data-data-storage-and-management-
for-ios-os-x-and-icloud-second-edition-marcus-s-zarra/
Introducing iOS 8 1st Edition Steve Derico
https://ebookfinal.com/download/introducing-ios-8-1st-edition-steve-
derico/
https://ebookfinal.com/download/learning-ios-ui-development-implement-
complex-ios-user-interfaces-with-ease-using-swift-1st-edition-
dareglia/
https://ebookfinal.com/download/swift-data-structure-and-
algorithms-1st-edition-azar/
https://ebookfinal.com/download/test-driven-ios-development-with-
swift-4-third-edition-dominik-hauser/
Learning Swift Building Apps for macOS iOS and Beyond 3rd
Edition Jonathon Manning
https://ebookfinal.com/download/learning-swift-building-apps-for-
macos-ios-and-beyond-3rd-edition-jonathon-manning/
Core Data by Tutorials iOS 8 and Swift Edition Aaron
Douglas Digital Instant Download
Author(s): Aaron Douglas, Saul Mora, Matthew Morey, Pietro Rea
ISBN(s): 9780989675192, 098967519X
File Details: PDF, 17.11 MB
Year: 2014
Language: english
Core Data by Tutorials
By the raywenderlich.com Tutorial Team
This book and all corresponding materials (such as source code) are provided
on an "as is" basis, without warranty of any kind, express or implied, including
but not limited to the warranties of merchantability, fitness for a particular
purpose, and noninfringement. In no event shall the authors or copyright
holders be liable for any claim, damages or other liability, whether in action of
contract, tort or otherwise, arising from, out of or in connec- tion with the
software or the use or other dealings in the software.
All trademarks and registered trademarks appearing in this book are the
property of their respective owners.
Table of Contents: Overview
Introduction .............................................................................................. 9!
Chapter 1: Your First Core Data App ............................................. 15!
Chapter 2: NSManagedObject Subclasses .................................... 33!
Chapter 3: The Core Data Stack ...................................................... 58!
Chapter 4: Intermediate Fetching .................................................... 79!
Chapter 5: NSFetchedResultsController ........................................ 111!
Chapter 6: Versioning and Migration ........................................... 134!
Chapter 7: Syncing with iCloud ...................................................... 170!
Chapter 8: Unit Testing..................................................................... 188!
Chapter 9: Measuring and Boosting Performance...................... 204!
Chapter 10: Multiple Managed Object Contexts ....................... 236!
Conclusion ............................................................................................ 256!
Table of Contents: Extended
Introduction .............................................................................................. 9!
What you need ............................................................................................. 10!
Who this book is for ..................................................................................... 10!
How to use this book..................................................................................... 11!
What’s in store ............................................................................................... 11!
Source code and forums .............................................................................. 12!
Updates........................................................................................................... 12!
License ............................................................................................................. 13!
About the authors .......................................................................................... 13!
About the editors ........................................................................................... 14!
Chapter 1: Your First Core Data App ............................................. 15!
Getting started .............................................................................................. 15!
Modeling your data ..................................................................................... 23!
Saving to Core Data .................................................................................... 26!
Fetching from Core Data ............................................................................. 30!
Where to go from here? .............................................................................. 32!
Chapter 2: NSManagedObject Subclasses .................................... 33!
Getting started .............................................................................................. 33!
Modeling your data ..................................................................................... 36!
Storing non-standard data types in Core Data ...................................... 39!
Managed object subclasses ........................................................................ 40!
Propagating a managed context .............................................................. 44!
Data validation in Core Data ..................................................................... 53!
Tying everything up ...................................................................................... 56!
Where to go from here? .............................................................................. 57!
Chapter 3: The Core Data Stack ...................................................... 58!
Getting started .............................................................................................. 58!
The managed object model ........................................................................ 60!
The persistent store ....................................................................................... 60!
The persistent store coordinator ................................................................. 61!
The managed object context ...................................................................... 61!
Creating your stack object .......................................................................... 62!
Modeling your data ..................................................................................... 66!
Adding managed object subclasses .......................................................... 70!
A walk down persistence lane .................................................................... 71!
Deleting objects from Core Data ............................................................... 76!
Where to go from here? .............................................................................. 78!
Chapter 4: Intermediate Fetching .................................................... 79!
NSFetchRequest: the star of the show ....................................................... 79!
Introducing the Bubble Tea app................................................................. 80!
Stored fetch requests.................................................................................... 82!
Fetching different result types .................................................................... 87!
Sorting fetched results ................................................................................ 103!
Asynchronous fetching ................................................................................ 105!
Batch updates: no fetching required ....................................................... 108!
Where to go from here? ............................................................................ 110!
Chapter 5: NSFetchedResultsController ........................................ 111!
Introducing the World Cup app ............................................................... 111!
It all begins with a fetch request... ........................................................... 113!
Grouping results into sections.................................................................... 119!
“Cache” the ball .......................................................................................... 123!
Monitoring changes ..................................................................................... 124!
Inserting an underdog ................................................................................ 129!
Where to go from here? ............................................................................ 133!
Chapter 6: Versioning and Migration ........................................... 134!
When to migrate ......................................................................................... 134!
The migration process................................................................................. 135!
Getting started ............................................................................................ 136!
A lightweight migration .............................................................................. 137!
A manual migration .................................................................................... 146!
A complex mapping model ....................................................................... 153!
Migrating non-sequential versions ........................................................... 159!
Where to go from here? ............................................................................ 169!
Chapter 7: Syncing with iCloud ...................................................... 170!
Getting started ............................................................................................ 171!
CloudNotes ................................................................................................... 172!
Enabling iCloud ........................................................................................... 173!
The cloud stack ............................................................................................ 175!
Testing iCloud .............................................................................................. 176!
Responding to iCloud changes.................................................................. 182!
Switching iCloud accounts .......................................................................... 184!
Where to go from here? ............................................................................ 187!
Chapter 8: Unit Testing..................................................................... 188!
Getting started ............................................................................................ 189!
Core Data stack for testing ....................................................................... 190!
Your first test ................................................................................................ 191!
Asynchronous tests ....................................................................................... 194!
Tests first ....................................................................................................... 196!
Validation and refactoring ....................................................................... 200!
Where to go from here? ............................................................................ 203!
Chapter 9: Measuring and Boosting Performance...................... 204!
Getting started ............................................................................................ 204!
Measure, change, verify ............................................................................ 207!
Fetching and performance ........................................................................ 217!
Where to go from here? ............................................................................ 235!
Chapter 10: Multiple Managed Object Contexts ....................... 236!
Getting started ............................................................................................ 236!
Doing work in the background ................................................................. 242!
Editing on a scratchpad ............................................................................. 248!
Where to go from here? ............................................................................ 254!
Conclusion ............................................................................................ 256!
Dedications
“To my partner, Mike, who supports all of the weirdness that is me.”
–Aaron Douglas
“To my Wife – without your tireless support behind the scenes, all my
work the world enjoys would not be possible.”
–Saul Mora
–Matthew Morey
–Pietro Rea
Introduction
By Greg Heo
What is Core Data? You'll hear a variety of answers to this question: It’s a
database! It's SQLite! It's not a database! And so forth.
Here's the technical answer: Core Data is an object graph management and
persistence framework in the OS X and iOS SDKs.
That means Core Data can store and retrieve data, but it is not a relational
database like MySQL or SQLite. Although it can use SQLite as the data store behind
the scenes, you don’t think about Core Data in terms of tables and rows and
primary keys.
Imagine you’re writing an app to keep track of dining habits. You have a varied set
of objects: restaurant objects, each with properties such as name and address;
categories, to organize the restaurants; and visits, to log each visit to a restaurant.
The object graph in memory might look something like this:
Object graph management means Core Data works with objects that you define,
such as the ones in the diagram above. For example, each restaurant (represented
by a red bubble) would have a property pointing back to the category object. It
would also have a property holding the list of visits.
raywenderlich.com Page 9
Core Data by Tutorials Introduction
Persistence means the data is stored somewhere durable such as the device’s
flash memory or “the cloud.” You point to the entire graph and just say “save.”
When your app launches, you just say “load” and the entire object graph pops up in
memory again, ready for use. That’s Core Data at work!
Maybe your users eat out a lot and have thousands of restaurant visits—rest
assured Core Data is smart about lazily loading objects and caching to optimize
both memory usage and speed.
Core Data has many other features aside from simply storing and fetching data:
You can perform custom filtering with predicates, sort the data and synchronize a
data store with iCloud, among other things. You’ll learn all about these features and
more in this book.
If you’re a complete beginner to iOS, we suggest you read through The iOS
Apprentice, 3rd Edition first. That will give you a solid foundation in building iOS
apps from the ground-up.
raywenderlich.com Page 10
Core Data by Tutorials Introduction
If you know the basics of iOS development but are new to Swift, we suggest you
read Swift by Tutorials first. That book has a similar hands-on approach and takes
you on a comprehensive tour through the Swift language.
If you’re new to Core Data or want to review the basics, we suggest you start with
Chapters 1–3. These chapters cover the fundamentals of Core Data and you’ll need
the knowledge in them to understand the rest of the book.
What’s in store
Here’s a quick summary of what you’ll find in each chapter:
1. Chapter 1, Your First Core Data App: You’ll click File\New Project and write
a Core Data app from scratch! This chapter covers the basics of setting up your
data model and then adding and fetching records.
2. Chapter 2, NSManagedObject Subclasses: NSManagedObject is the base data
storage class of your Core Data object graphs. This chapter will teach you how
you customize your own managed object subclasses to store and validate data.
3. Chapter 3, The Core Data Stack: Under the hood, Core Data is made up of
many parts working together. In this chapter, you’ll learn about how these parts
fit together, and move away from the starter Xcode template to build your own
customizable system.
4. Chapter 4, Intermediate Fetching: Your apps will fetch data all the time, and
Core Data offers many options for getting the data to you efficiently. This chapter
covers more advanced fetch requests, predicates, sorting and asynchronous
fetching.
5. Chapter 5, NSFetchedResultsController: Table views are at the core of many
iOS apps, and Apple wants to make Core Data play nicely with them! In this
chapter, you’ll learn how NSFetchedResultsController can save you time and code
when your table views are backed by data from Core Data.
raywenderlich.com Page 11
Core Data by Tutorials Introduction
6. Chapter 6, Versioning and Migration: As you update and enhance your app,
its data model will almost certainly need to change. In this chapter, you’ll learn
how to create multiple versions of your data model and then migrate your users
forward so they can keep their existing data as they upgrade.
7. Chapter 7, Syncing with iCloud: Move beyond storing data locally on a single
device, to cloud storage and synchronizing across all the user’s devices. This
chapter covers how to extend an existing Core Data app to use iCloud.
8. Chapter 8, Unit Tests: Testing is an important part of the development
process, and you shouldn’t leave Core Data out of those tests! In this chapter,
you’ll learn how to set up a separate test environment for Core Data and see
examples of how to test your models.
9. Chapter 9, Measuring and Boosting Performance: No one ever complained
that an app was too fast, so it’s important to be vigilant about tracking
performance. In this chapter, you’ll learn how to measure your app’s performance
with various Xcode tools and then pick up some tips for dealing with slow spots in
your code.
10. Chapter 10, Multiple Managed Object Contexts: In this final chapter, you’ll
expand the usual Core Data stack to include multiple managed object contexts.
You’ll learn how this can improve perceived performance and help make your app
architecture less monolithic and more compartmentalized.
Updates
Since you’ve purchased the PDF version of this book, you get free access to any
updates we make to the book!
The best way to get update notifications is to sign up for our monthly newsletter.
This includes a list of the tutorials that came out on raywenderlich.com that month,
any important news like book updates or new books, and a list of our favorite
development links for that month. You can sign up at this URL:
http://www.raywenderlich.com/newsletter
raywenderlich.com Page 12
Core Data by Tutorials Introduction
License
By purchasing Core Data by Tutorials, you have the following license:
• You are allowed to use and/or modify the source code in Core Data by Tutorials in
as many apps as you want, with no attribution required.
• You are allowed to use and/or modify all art, images and designs that are included
in Core Data by Tutorials in as many apps as you want, but must include this
attribution line somewhere inside your app: “Artwork/images/designs: from Core
Data by Tutorials book, available at http://www.raywenderlich.com.”
• The source code included in Core Data by Tutorials is for your personal use only.
You are NOT allowed to distribute or sell the source code in Core Data by
Tutorials without prior authorization.
• This book is for your personal use only. You are NOT allowed to sell this book
without prior authorization or distribute it to friends, co-workers or students; they
would need to purchase their own copies.
All materials provided with this book are provided on an “as is” basis, without
warranty of any kind, express or implied, including but not limited to the warranties
of merchantability, fitness for a particular purpose and non-infringement. In no
event shall the authors or copyright holders be liable for any claim, damages or
other liability, whether in an action of contract, tort or otherwise, arising from, out
of or in connection with the software or the use or other dealings in the software.
All trademarks and registered trademarks appearing in this book are the property of
their respective owners.
raywenderlich.com Page 13
Core Data by Tutorials Introduction
Bradley C. Phillips was the editor for this book, and was
the first editor to come aboard at raywenderlich.com. He
has worked as a journalist and previously directed the
intelligence department of an investigative firm in New
York City. Right now, Bradley works freelance and pursues
his own projects. Contact him if you need a skilled and
experienced editor for your blog, books or anything else.
Greg Heo was the final pass editor for this book, and has
been part of the editorial team at raywenderlich.com since
2012.
raywenderlich.com Page 14
Chapter 1: Your First Core
Data App
By Pietro Rea
Welcome to Core Data! In this chapter, you’ll write your very first Core Data app.
You’ll see how easy it is to get started with all the resources provided in Xcode,
from the starter code templates to the data model editor.
You’re going to hit the ground running right from the first chapter in this book; by
the end of the chapter you’ll know how to:
• model data you want to store in Core Data using Xcode’s model editor;
• add new records to Core Data;
• fetch a set of records from Core Data; and
• display the fetched results to the user in a table view.
You’ll also get a sense of what Core Data is doing behind the scenes, and how you
can interact with the various moving pieces there. This will put you well on your
way to understanding the next two chapters, which continue the introduction to
Core Data with more advanced models and data validation, amongst other things.
Getting started
Open Xcode and create a new iPhone project based on the Single View
Application template. Call the app HitList and make sure Use Core Data is
checked:
raywenderlich.com Page 15
Core Data by Tutorials Chapter 1: Your First Core Data App
Checking the Use Core Data box will cause Xcode to generate boilerplate code for
what’s known as a Core Data stack in AppDelegate.swift.
The Core Data stack consists of a set of objects that facilitate saving and retrieving
information from Core Data. There’s an object to manage the Core Data state as a
whole, an object representing the data model, and so on.
You’ll learn about each of these pieces in these first few chapters. Later, you’ll even
have the chance to write your own Core Data stack! The standard stack works just
fine for many apps but based on your app and its data, you can customize the stack
to be more efficient.
Note: Not all Xcode templates have the option to start with Core Data. In
Xcode 6, only the Master-Detail Application and the Single View
Application templates have the Use Core Data checkbox.
The idea for this sample app is simple. There will be a table view with a list of
names for your very own “hit list”. You’ll be able to add names to this list and
eventually, you’ll use Core Data to make sure the data is stored between sessions.
We don’t condone violence in this book so you can think of this app as a “favorites
list” to keep track of your friends too, of course! ;]
raywenderlich.com Page 16
Core Data by Tutorials Chapter 1: Your First Core Data App
Next, embed the view controller in a navigation controller. From Xcode’s Editor
menu, select Embed In…\ Navigation Controller.
Back in Interface Builder, drag a Table View from the object library into the view
controller so that it covers the entire view.
Then, drag a Bar Button Item and place it on the view controller’s newly added
navigation bar. Finally, double-click the bar button item to change its text to Add.
Your canvas should now look like the following screenshot:
Every time you tap Add on the top-right, an alert containing a text field will appear
on the screen. From there you’ll be able to type someone’s name into the text field.
Dismissing the alert will save the name and refresh the table view with all the
names you’ve saved up to that point.
raywenderlich.com Page 17
Core Data by Tutorials Chapter 1: Your First Core Data App
Before you can do that, you need to make the view controller the table view’s data
source. Ctrl-drag from the table view to the yellow view controller icon above the
navigation bar, as shown below, and click on dataSource:
In case you were wondering, you don’t need to set up the table view’s delegate
since tapping on the cells won’t trigger any action. It doesn’t get simpler than this!
Name the new IBOutlet property tableView, resulting in the following line:
Ctrl-drag from the Add bar button item onto ViewController.swift, but this time,
create an action instead of an outlet and name the method addName:
You can now refer to the table view and the bar button item’s action in code. Next,
set up the model for the table view. Add the following property to
ViewController.swift:
names is a mutable Array to hold the strings for the table view to display.
raywenderlich.com Page 18
Core Data by Tutorials Chapter 1: Your First Core Data App
This will set a title and register the UITableViewCell class with the table view. You
do this so that when you dequeue a cell, the table view will return a cell of the
correct type.
// MARK: UITableViewDataSource
func tableView(tableView: UITableView,
numberOfRowsInSection section: Int) -> Int {
return names.count
}
let cell =
tableView.dequeueReusableCellWithIdentifier("Cell")
as UITableViewCell
cell.textLabel!.text = names[indexPath.row]
return cell
}
If you’ve ever worked with UITableView, this code should look very familiar. The
first method says that the table view will have as many rows as the names array has
strings.
raywenderlich.com Page 19
Core Data by Tutorials Chapter 1: Your First Core Data App
Don’t run the app just yet. First, you need a way to input names so the table view
can display them.
Implement the addName IBAction method you Ctrl-dragged into your code earlier:
alert.addTextFieldWithConfigurationHandler {
(textField: UITextField!) -> Void in
}
alert.addAction(saveAction)
alert.addAction(cancelAction)
presentViewController(alert,
animated: true,
completion: nil)
}
Every time you tap the Add bar button item, this method presents an
UIAlertController with a text field and two buttons, Save and Cancel.
Save takes whatever text is currently in the text field, inserts it into the name array
and reloads the table view. Since the names array is the model backing the table
view, whatever you typed into the text field will appear in the table view.
Finally it’s time to build and run your app for the first time. Tap the Add bar button
item. The alert controller will look like this:
raywenderlich.com Page 20
Discovering Diverse Content Through
Random Scribd Documents
carrying the rifle with him—not an easy feat by any means even for a
sailor!
It seemed to me that the fierce dog only took a couple of
prodigious bounds, and then sprang deliberately at Ned, utterly
regardless of the deadly sword blade. Like a man-eating tiger, he
evidently relied upon his weight and the suddenness of his attack.
I saw my coxswain aim a blow at the huge brute as it rushed in
upon him; but the next instant I saw him borne backwards to the
ground as the animal closed with him. At the same instant I caught
sight of the gunner raising his rifle to his shoulder as if with the
intention of blowing out the bloodhound’s brains.
It was no longer a dream, but a living tragical reality; and there
was I, safely ensconced in a tree, while my daring shipmates were
fighting for their lives with what was practically a savage wild beast!
Of course I saw now that Ned had unselfishly wished to place us in
safety before confronting the bloodhound single-handed. Recalled to
myself, and anxious to lend any assistance that lay in my power, I
hastily commenced to descend the tree; but as ill-luck would have it,
I grasped a rotten branch, which came away in my hand, and I was
precipitated to the ground—fortunately from no great height. As I fell,
I fancied I heard loud snarling and a deep moan. The next instant I
was on my feet again, feeling rather confused, but having suffered
nothing but one or two bruises. I was immensely relieved by the sight
that met my gaze, which made an impressive tableau.
The bloodhound lay stretched out on the ground, stone-dead, with
a puncture in the region of the heart. Ned was kneeling on the
ground close to the body of his assailant, and holding a gory sword
in his right hand. Leaning upon his rifle, and gazing down at the
defunct beast, stood Mr. Triggs.
“’Tis a good job, Ned,” the latter was saying, “that I didn’t let fly at
the beast. The report of my rifle would have brought a nest of
hornets about our ears, I’m thinking.”
“That it would,” answered my coxswain, wiping his sword in a
tussock of long grass; “but how it is them swabs have got separated
from their dog beats me.”
“Well, it’s the fortune of war,” said the gunner grimly, “and we must
be thankful for it. At the same time, mind you, they may not be a
hundred miles away, and we had better make ourselves scarce, and
steer for the sea-shore with steam up in all boilers.”
Ned sprang to his feet, and after inquiring of me whether I was
hurt by my fall out of the tree, he proposed that we should secrete
the bloodhound’s body for fear it should be discovered by the
pirates.
This was good advice, and we proceeded to act upon it. The dog’s
body was cumbrous and heavy, but by our united exertions we
dragged it to the edge of a neighbouring ravine and cast it down. As
this particular chasm was fringed with bushes and underwood, it
would not have been an easy matter to detect anything lying among
the rocks at the bottom of it.
I told my shipmates that I felt sure that if the other bloodhound was
still at large, it would be certain, sooner or later, to scent out Ned’s
victim.
The latter, we knew, was the pirate chief’s bloodhound, as we had
instantly recognized it by its mutilated ear.
“Flaying alive would be too good for me now if ever I’m nobbled,”
said Ned, as we once more set out at a sharp run; “leastways if that
cut-throat head of the gang knew that I’d settled the hash of his
highly prized bow-wow.”
“How did you manage to kill the brute?” I asked. “It was an awful
sight to see it fly at you, and I thought I saw it knock you over.”
“Well, it just did bowl me over and no mistake, sir, but I fancied
that something better was in store for me than to be popped off by a
furriner’s dog, and so I kept as cool as a cowcumber, and let drive
with the sword just as the beast was on top of me, as it were. My
killing it was a bit of a fluke, there’s no denying that, for I didn’t know
the bearings of his heart in the least.”
“You’ve rid us of our worst foe, Ned,” I said, “and given us a much
better chance of escape.”
“That was in my mind, of course,” said the seaman. “Thinks I to
myself, ‘Here’s that blooming dog close astarn of us, and somehow
got separated from his mate and his owners. What a chance to put
him out of the way on the quiet! Jiggered if I don’t slit his weasand
for him.’ Well, I did something more effectual than that, Mr. Darcy;
and here we are, with a fair start again, and I hopes as how we’ll
stick to it.”
It certainly seemed like a turning-point in our fortunes; for though
we even now heard some occasional shouts, they seemed to be at a
considerable distance, and we could not detect any baying from the
other bloodhound. I do not know whether I mentioned the fact
before, but I had been rather sceptical as to this latter animal being
upon our trail at all—at any rate during the last half-hour.
We still suffered a great deal of discomfort from our wet clothes
and boots, but we ran gamely on, knowing that everything depended
on our speed.
At length, without further misadventure, we emerged from the
jungle, and found ourselves on a rather extensive expanse of
sandhills, beyond which lay the blue sea, still darkened by the dun
volcanic clouds which hung in mid-air.
“Is that a boat?” asked Ned, excitedly.
CHAPTER XXIII.
A RACE FOR LIFE.
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
ebookfinal.com