SlideShare a Scribd company logo
1 of 23
Download to read offline
Simpler Core Data
with RubyMotion
StefĆ”n Haļ¬‚iĆ°ason
http://stefan.haļ¬‚idason.com
@styrmis
Why RubyMotion?
ā€¢ Promises increased developer productivity
ā€¢ Brings the ļ¬‚exibility of Ruby to iOS and OSX development
ā€¢ Bridges directly to Obj-C libraries: no intermediate glue
code
ā€¢ A REPL for working with your app live!
ā€¢ Make tweaks quickly
ā€¢ Build whole views programmatically on the ļ¬‚y
Why Core Data?
ā€¢ Optimised for low-memory/embedded (iOS)
devices
ā€¢ Mature data access/persistence framework
ā€¢ Also available on OSX
ā€¢ Works with iCloudā€”free cloud syncing for your
app
Core Data is Difļ¬cult
ā€¢ Provided boilerplate code unnecessarily complex
ā€¢ An object graph thatā€™s persisted to an SQLite
database
ā€¢ Suggests relational access, which is not quite
the case
ā€¢ Typical patterns for working with relational data
are not optimal here
RubyMotion is ā€œEasyā€
ā€¢ Friendliness of Ruby
ā€¢ An ARC equivalent is included
ā€¢ Lots of work done to abstract complexity away
ā€¢ More concepts similar to other OO languages
Core Data and RubyMotion
ā€¢ No equivalent of Xcodeā€™s visual data modeller
ā€¢ How do I deļ¬ne my data model?!
ā€¢ What about versioning?!
ā€¢ How will I handle migrations?
What we need
ā€¢ Our data model (NSEntityDescriptions +
NSRelationshipDescriptions forming our
NSManagedObject)
ā€¢ A Core Data Stack (NSManagedObjectModel +
NSPersistentStoreCoordinator +
NSManagedObjectContext)
ā€¢ A workļ¬‚ow for versioning and migrating
between versions
Deļ¬ning Our Data Model
ā€¢ We would normally do this in Xcode
ā€¢ Visual Editor for .xcdatamodel bundles
ā€¢ Integrated handling of versioning and custom
migration code
ā€¢ Automatic lightweight (schema) migrations
ā€¢ How do we achieve this with RubyMotion?
Options for RubyMotion
ā€¢ Handle everything programmatically (low
level)
ā€¢ Use Xcode to work with .xcdatamodel ļ¬les,
copy in each time
ā€¢ Use a Ruby library for creating .xcdatamodel
ļ¬les
Handling Everything
Programmatically
entity = NSEntityDescription.alloc.init	
entity.name = 'Task'	
entity.managedObjectClassName = 'Task'	
entity.properties =	
[ 'task_description', NSStringAttributeType,	
'completed', NSBooleanAttributeType ].each_slice(2).map do |name, type|	
property = NSAttributeDescription.alloc.init	
property.name = name	
property.attributeType = type	
property.optional = false	
property	
end
Handling Everything
Programmatically
entity = NSEntityDescription.alloc.init	
entity.name = 'Task'	
entity.managedObjectClassName = 'Task'	
entity.properties =	
[ 'task_description', NSStringAttributeType,	
'completed', NSBooleanAttributeType ].each_slice(2).map do |name, type|	
property = NSAttributeDescription.alloc.init	
property.name = name	
property.attributeType = type	
property.optional = false	
property	
end
Not all that bad, but we want to use .xcdatamodel ļ¬les
.xcdatamodel ļ¬les are just
XML
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>!
<model name="" userDefinedModelVersionIdentifier="001"
type="com.apple.IDECoreDataModeler.DataModel" documentVersion="1.0"
lastSavedToolsVersion="2061" systemVersion="12D78"
minimumToolsVersion="Xcode 4.3" macOSVersion="Automatic"
iOSVersion="Automatic">!
<entity name="Article" syncable="YES">!
<attribute name="title" optional="YES" attributeType="String"
syncable="YES"/>!
<relationship name="author" optional="YES" minCount="1"
maxCount="1" deletionRule="Nullify" destinationEntity="Author"
inverseName="articles" inverseEntity="Article" syncable="YES"/>!
</entity>!
<entity name="Author" syncable="YES">!
<attribute name="name" optional="YES" attributeType="String"
syncable="YES"/>!
<relationship name="articles" optional="YES" minCount="1"
maxCount="1" deletionRule="Nullify" destinationEntity="Article"
inverseName="author" inverseEntity="Author" syncable="YES"/>!
</entity>!
</model>
Using a library to generate
.xcdatamodel ļ¬les (ruby-xcdm)
1 schema "001" do!
2 entity "Article" do!
3 string :body, optional: false!
4 integer32 :length!
5 boolean :published, default: false!
6 datetime :publishedAt, default: false!
7 string :title, optional: false!
8 !
9 belongs_to :author!
10 end!
11 !
12 entity "Author" do!
13 float :fee!
14 string :name, optional: false!
15 has_many :articles!
16 end!
17 end
Workļ¬‚ow
ā€¢ Create schema ļ¬le in schemas directory, e.g.
schemas/001_initial.rb
ā€¢ Build the schema
ā€¢ Add a new schema version, e.g.
002_add_new_fields.rb
ā€¢ Rebuild the schema
ā€¢ Thatā€™s it!
Workļ¬‚ow
$ echo "gem 'ruby-xcdm', '0.0.5'" >> Gemfile	
$ bundle install	
$ rake schema:build	
Generating Data Model learn-xcdm	
Loading schemas/001_initial.rb	
Writing resources/learn-xcdm.xcdatamodeld/1.xcdatamodel/
contents	
$ rake # The default rake task is to run the app in the simulator	
(main)> mom = NSManagedObjectModel.mergedModelFromBundles(nil)	
=> #<NSManagedObjectModel:0x8fa7690>	
(main)> mom.entities.count	
=> 2	
(main)> mom.entities.first.name	
=> "Article"	
(main)> mom.entities.first.propertiesByName	
=> {"body"=>#<NSAttributeDescription:0x8e5db30>,
"title"=>#<NSAttributeDescription:0x8ea4770>}
Advantages of using ruby-
xcdm
ā€¢ No magic: generates XML from a schema
ā€¢ Schema versions are fully text-based and
readable, making them well-suited to version
control
ā€¢ Can compile our versions into .xcdatamodeld
bundles, completely removing dependence on
Xcode
Basic Core Data Stack
1 model = NSManagedObjectModel.mergedModelFromBundles(nil)	
2 	
3 store = NSPersistentStoreCoordinator.alloc.initWithManagedObjectModel(model)	
4 store_path = File.join(NSHomeDirectory(), 'Documents', 'LearnXcdm.sqlite')	
5 store_url = NSURL.fileURLWithPath(store_path)	
6 	
7 options = { NSMigratePersistentStoresAutomaticallyOption => true,	
8 NSInferMappingModelAutomaticallyOption => true }	
9 	
10 error_ptr = Pointer.new(:object)	
11 	
12 unless store.addPersistentStoreWithType(NSSQLiteStoreType,	
13 configuration: nil,	
14 URL: store_url,	
15 options: options,	
16 error: error_ptr)	
17 raise "[ERROR] Failed to create persistent store: #{error_ptr[0].description}"	
18 end	
19 	
20 @context = NSManagedObjectContext.alloc.init	
21 @context.persistentStoreCoordinator = store
Core Data Query
ā€¢ From the developers of ruby-xcdm
ā€¢ Abstracts away much of the complexity of Core
Data
ā€¢ All you need is your .xcdatamodeld bundle
Core Data Query in Action
# app/models/task.rb	
class Task < CDQManagedObject	
end	
!
# app/app_delegate.rb	
class AppDelegate	
include CDQ	
!
def application(application,
didFinishLaunchingWithOptions:launchOptions)	
cdq.setup	
true	
end	
end
Core Data Query in Action
(main)> Task.count	
=> 0	
(main)> t1 = Task.create(task_description: "Complete presentation")	
(main)> t2 = Task.create(task_description: "File tax return")	
(main)> cdq.save	
=> true	
(main)> exit	
$ rake	
...	
(main)> Task.count	
=> 2	
(main)> t1, t2 = Task.all.array	
(main)> t1.task_description	
=> "Complete chapter"	
(main)> t2.task_description	
=> "File tax return"	
(main)> t2.destroy	
=> #<NSManagedObjectContext:0x914cbe0>	
(main)> cdq.save	
=> true	
(main)> Task.count	
=> 1
Core Data in Action
Author.where(:name).eq("Emily")	
Author.where(:name).not_equal("Emily")	
Author.limit(1)	
Author.offset(10)	
Author.where(:name).contains("A").offset(10).first	
!
# Conjuctions	
Author.where(:name).contains("Emily").and.contains("Dickinson")	
Author.where(:name).starts_with("E").or(:pub_count).eq(1)	
!
# Nested Conjuctions	
Author.where(:name).contains("Emily").and(cdq(:pub_count).gt(100).or.lt(10)
)	
!
# Relationships	
Author.first.publications.offset(2).limit(1)	
cdq(emily_dickinson).publications.where(:type).eq('poetry')	
!
class Author < CDQManagedObject	
scope :prolific, where(:pub_count).gt(50)	
end
Takeaways
ā€¢ Donā€™t be put off by the Xcode boilerplate: Core
Data doesnā€™t have to be that hard
ā€¢ With CDQ, Core Data is arguably easier to use
with RubyMotion rather than harder
ā€¢ XCDM, CDQ and RubyMotion Query (all by
Inļ¬nitered) are all worth taking a look at
Next Steps
ā€¢ In the coming weeks Iā€™ll be researching and writing
about:
ā€¢ How to best handle heavyweight/data migrations
in RubyMotion
ā€¢ Deconstructing the ā€˜magicā€™ in Core Data Query
ā€¢ RubyMotion development best practices
StefĆ”n Haļ¬‚iĆ°ason
http://stefan.haļ¬‚idason.com
@styrmis

More Related Content

What's hot

Intro to node.js - Ran Mizrahi (28/8/14)
Intro to node.js - Ran Mizrahi (28/8/14)Intro to node.js - Ran Mizrahi (28/8/14)
Intro to node.js - Ran Mizrahi (28/8/14)Ran Mizrahi
Ā 
Getting Started with Web
Getting Started with WebGetting Started with Web
Getting Started with WebAkshay Mathur
Ā 
MVS: An angular MVC
MVS: An angular MVCMVS: An angular MVC
MVS: An angular MVCDavid Rodenas
Ā 
The Naked Bundle - Tryout
The Naked Bundle - TryoutThe Naked Bundle - Tryout
The Naked Bundle - TryoutMatthias Noback
Ā 
How AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design PatternsHow AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design PatternsRan Mizrahi
Ā 
Digital Ocean Presentation - Ruby Dev Stackup - The Flatiron School
Digital Ocean Presentation - Ruby Dev Stackup - The Flatiron School Digital Ocean Presentation - Ruby Dev Stackup - The Flatiron School
Digital Ocean Presentation - Ruby Dev Stackup - The Flatiron School Elana Jacobs
Ā 
Arquitetando seu app Android com Jetpack
Arquitetando seu app Android com JetpackArquitetando seu app Android com Jetpack
Arquitetando seu app Android com JetpackNelson Glauber Leal
Ā 
Understanding backbonejs
Understanding backbonejsUnderstanding backbonejs
Understanding backbonejsNick Lee
Ā 
Intro to Scala.js - Scala UG Cologne
Intro to Scala.js - Scala UG CologneIntro to Scala.js - Scala UG Cologne
Intro to Scala.js - Scala UG CologneMarius Soutier
Ā 
Art of Javascript
Art of JavascriptArt of Javascript
Art of JavascriptTarek Yehia
Ā 
Ember.js - A JavaScript framework for creating ambitious web applications
Ember.js - A JavaScript framework for creating ambitious web applications  Ember.js - A JavaScript framework for creating ambitious web applications
Ember.js - A JavaScript framework for creating ambitious web applications Juliana Lucena
Ā 
jQuery Objects
jQuery ObjectsjQuery Objects
jQuery ObjectsSteve Wells
Ā 
[Srijan Wednesday Webinars] Ruling Drupal 8 with #d8rules
[Srijan Wednesday Webinars] Ruling Drupal 8 with #d8rules[Srijan Wednesday Webinars] Ruling Drupal 8 with #d8rules
[Srijan Wednesday Webinars] Ruling Drupal 8 with #d8rulesSrijan Technologies
Ā 
Internet and Web Technology (CLASS-10) [Node.js] | NIC/NIELIT Web Technology
Internet and Web Technology (CLASS-10) [Node.js] | NIC/NIELIT Web Technology Internet and Web Technology (CLASS-10) [Node.js] | NIC/NIELIT Web Technology
Internet and Web Technology (CLASS-10) [Node.js] | NIC/NIELIT Web Technology Ayes Chinmay
Ā 
Workshop 12: AngularJS Parte I
Workshop 12: AngularJS Parte IWorkshop 12: AngularJS Parte I
Workshop 12: AngularJS Parte IVisual Engineering
Ā 
Hi performance table views with QuartzCore and CoreText
Hi performance table views with QuartzCore and CoreTextHi performance table views with QuartzCore and CoreText
Hi performance table views with QuartzCore and CoreTextMugunth Kumar
Ā 
SenchaCon 2016: How to Auto Generate a Back-end in Minutes - Per Minborg, Emi...
SenchaCon 2016: How to Auto Generate a Back-end in Minutes - Per Minborg, Emi...SenchaCon 2016: How to Auto Generate a Back-end in Minutes - Per Minborg, Emi...
SenchaCon 2016: How to Auto Generate a Back-end in Minutes - Per Minborg, Emi...Sencha
Ā 
Viking academy backbone.js
Viking academy  backbone.jsViking academy  backbone.js
Viking academy backbone.jsBert Wijnants
Ā 

What's hot (20)

Intro to node.js - Ran Mizrahi (28/8/14)
Intro to node.js - Ran Mizrahi (28/8/14)Intro to node.js - Ran Mizrahi (28/8/14)
Intro to node.js - Ran Mizrahi (28/8/14)
Ā 
Getting Started with Web
Getting Started with WebGetting Started with Web
Getting Started with Web
Ā 
MVS: An angular MVC
MVS: An angular MVCMVS: An angular MVC
MVS: An angular MVC
Ā 
The Naked Bundle - Tryout
The Naked Bundle - TryoutThe Naked Bundle - Tryout
The Naked Bundle - Tryout
Ā 
How AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design PatternsHow AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design Patterns
Ā 
Digital Ocean Presentation - Ruby Dev Stackup - The Flatiron School
Digital Ocean Presentation - Ruby Dev Stackup - The Flatiron School Digital Ocean Presentation - Ruby Dev Stackup - The Flatiron School
Digital Ocean Presentation - Ruby Dev Stackup - The Flatiron School
Ā 
Arquitetando seu app Android com Jetpack
Arquitetando seu app Android com JetpackArquitetando seu app Android com Jetpack
Arquitetando seu app Android com Jetpack
Ā 
Understanding backbonejs
Understanding backbonejsUnderstanding backbonejs
Understanding backbonejs
Ā 
JS Essence
JS EssenceJS Essence
JS Essence
Ā 
Intro to Scala.js - Scala UG Cologne
Intro to Scala.js - Scala UG CologneIntro to Scala.js - Scala UG Cologne
Intro to Scala.js - Scala UG Cologne
Ā 
Art of Javascript
Art of JavascriptArt of Javascript
Art of Javascript
Ā 
Ember.js - A JavaScript framework for creating ambitious web applications
Ember.js - A JavaScript framework for creating ambitious web applications  Ember.js - A JavaScript framework for creating ambitious web applications
Ember.js - A JavaScript framework for creating ambitious web applications
Ā 
jQuery Objects
jQuery ObjectsjQuery Objects
jQuery Objects
Ā 
[Srijan Wednesday Webinars] Ruling Drupal 8 with #d8rules
[Srijan Wednesday Webinars] Ruling Drupal 8 with #d8rules[Srijan Wednesday Webinars] Ruling Drupal 8 with #d8rules
[Srijan Wednesday Webinars] Ruling Drupal 8 with #d8rules
Ā 
Internet and Web Technology (CLASS-10) [Node.js] | NIC/NIELIT Web Technology
Internet and Web Technology (CLASS-10) [Node.js] | NIC/NIELIT Web Technology Internet and Web Technology (CLASS-10) [Node.js] | NIC/NIELIT Web Technology
Internet and Web Technology (CLASS-10) [Node.js] | NIC/NIELIT Web Technology
Ā 
Workshop 12: AngularJS Parte I
Workshop 12: AngularJS Parte IWorkshop 12: AngularJS Parte I
Workshop 12: AngularJS Parte I
Ā 
Hi performance table views with QuartzCore and CoreText
Hi performance table views with QuartzCore and CoreTextHi performance table views with QuartzCore and CoreText
Hi performance table views with QuartzCore and CoreText
Ā 
SenchaCon 2016: How to Auto Generate a Back-end in Minutes - Per Minborg, Emi...
SenchaCon 2016: How to Auto Generate a Back-end in Minutes - Per Minborg, Emi...SenchaCon 2016: How to Auto Generate a Back-end in Minutes - Per Minborg, Emi...
SenchaCon 2016: How to Auto Generate a Back-end in Minutes - Per Minborg, Emi...
Ā 
Java script
Java scriptJava script
Java script
Ā 
Viking academy backbone.js
Viking academy  backbone.jsViking academy  backbone.js
Viking academy backbone.js
Ā 

Similar to Simpler Core Data with RubyMotion

iOSDevCamp 2011 Core Data
iOSDevCamp 2011 Core DataiOSDevCamp 2011 Core Data
iOSDevCamp 2011 Core DataChris Mar
Ā 
Connecting to a REST API in iOS
Connecting to a REST API in iOSConnecting to a REST API in iOS
Connecting to a REST API in iOSgillygize
Ā 
CocoaHeads PDX 2014 01 23 : CoreData and iCloud Improvements iOS7 / OSX Maver...
CocoaHeads PDX 2014 01 23 : CoreData and iCloud Improvements iOS7 / OSX Maver...CocoaHeads PDX 2014 01 23 : CoreData and iCloud Improvements iOS7 / OSX Maver...
CocoaHeads PDX 2014 01 23 : CoreData and iCloud Improvements iOS7 / OSX Maver...smn-automate
Ā 
Core data orlando i os dev group
Core data   orlando i os dev groupCore data   orlando i os dev group
Core data orlando i os dev groupAndrew Kozlik
Ā 
Core Data with Swift 3.0
Core Data with Swift 3.0Core Data with Swift 3.0
Core Data with Swift 3.0Korhan Bircan
Ā 
PofEAA and SQLAlchemy
PofEAA and SQLAlchemyPofEAA and SQLAlchemy
PofEAA and SQLAlchemyInada Naoki
Ā 
Intro to Core Data
Intro to Core DataIntro to Core Data
Intro to Core DataMake School
Ā 
REST/JSON/CoreData Example Code - A Tour
REST/JSON/CoreData Example Code - A TourREST/JSON/CoreData Example Code - A Tour
REST/JSON/CoreData Example Code - A TourCarl Brown
Ā 
Real World MVC
Real World MVCReal World MVC
Real World MVCJames Johnson
Ā 
Intro to IndexedDB (Beta)
Intro to IndexedDB (Beta)Intro to IndexedDB (Beta)
Intro to IndexedDB (Beta)Mike West
Ā 
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...The Magic Revealed: Four Real-World Examples of Using the Client Object Model...
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...SPTechCon
Ā 
Node.js Patterns for Discerning Developers
Node.js Patterns for Discerning DevelopersNode.js Patterns for Discerning Developers
Node.js Patterns for Discerning Developerscacois
Ā 
Core Data Performance Guide Line
Core Data Performance Guide LineCore Data Performance Guide Line
Core Data Performance Guide LineGagan Vishal Mishra
Ā 
iOS App with Parse.com as RESTful Backend
iOS App with Parse.com as RESTful BackendiOS App with Parse.com as RESTful Backend
iOS App with Parse.com as RESTful BackendStefano Zanetti
Ā 
Core Data Migrations and A Better Option
Core Data Migrations and A Better OptionCore Data Migrations and A Better Option
Core Data Migrations and A Better OptionPriya Rajagopal
Ā 
MFF UK - Introduction to iOS
MFF UK - Introduction to iOSMFF UK - Introduction to iOS
MFF UK - Introduction to iOSPetr Dvorak
Ā 
Rails and iOS with RestKit
Rails and iOS with RestKitRails and iOS with RestKit
Rails and iOS with RestKitAndrew Culver
Ā 

Similar to Simpler Core Data with RubyMotion (20)

iOSDevCamp 2011 Core Data
iOSDevCamp 2011 Core DataiOSDevCamp 2011 Core Data
iOSDevCamp 2011 Core Data
Ā 
Connecting to a REST API in iOS
Connecting to a REST API in iOSConnecting to a REST API in iOS
Connecting to a REST API in iOS
Ā 
CocoaHeads PDX 2014 01 23 : CoreData and iCloud Improvements iOS7 / OSX Maver...
CocoaHeads PDX 2014 01 23 : CoreData and iCloud Improvements iOS7 / OSX Maver...CocoaHeads PDX 2014 01 23 : CoreData and iCloud Improvements iOS7 / OSX Maver...
CocoaHeads PDX 2014 01 23 : CoreData and iCloud Improvements iOS7 / OSX Maver...
Ā 
Core data orlando i os dev group
Core data   orlando i os dev groupCore data   orlando i os dev group
Core data orlando i os dev group
Ā 
Core Data with Swift 3.0
Core Data with Swift 3.0Core Data with Swift 3.0
Core Data with Swift 3.0
Ā 
PofEAA and SQLAlchemy
PofEAA and SQLAlchemyPofEAA and SQLAlchemy
PofEAA and SQLAlchemy
Ā 
Intro to Core Data
Intro to Core DataIntro to Core Data
Intro to Core Data
Ā 
Core data optimization
Core data optimizationCore data optimization
Core data optimization
Ā 
REST/JSON/CoreData Example Code - A Tour
REST/JSON/CoreData Example Code - A TourREST/JSON/CoreData Example Code - A Tour
REST/JSON/CoreData Example Code - A Tour
Ā 
Real World MVC
Real World MVCReal World MVC
Real World MVC
Ā 
Intro to IndexedDB (Beta)
Intro to IndexedDB (Beta)Intro to IndexedDB (Beta)
Intro to IndexedDB (Beta)
Ā 
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...The Magic Revealed: Four Real-World Examples of Using the Client Object Model...
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...
Ā 
Slickdemo
SlickdemoSlickdemo
Slickdemo
Ā 
Node.js Patterns for Discerning Developers
Node.js Patterns for Discerning DevelopersNode.js Patterns for Discerning Developers
Node.js Patterns for Discerning Developers
Ā 
Core Data Performance Guide Line
Core Data Performance Guide LineCore Data Performance Guide Line
Core Data Performance Guide Line
Ā 
iOS App with Parse.com as RESTful Backend
iOS App with Parse.com as RESTful BackendiOS App with Parse.com as RESTful Backend
iOS App with Parse.com as RESTful Backend
Ā 
Core Data Migrations and A Better Option
Core Data Migrations and A Better OptionCore Data Migrations and A Better Option
Core Data Migrations and A Better Option
Ā 
MFF UK - Introduction to iOS
MFF UK - Introduction to iOSMFF UK - Introduction to iOS
MFF UK - Introduction to iOS
Ā 
Week3
Week3Week3
Week3
Ā 
Rails and iOS with RestKit
Rails and iOS with RestKitRails and iOS with RestKit
Rails and iOS with RestKit
Ā 

Recently uploaded

04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
Ā 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
Ā 
šŸ¬ The future of MySQL is Postgres šŸ˜
šŸ¬  The future of MySQL is Postgres   šŸ˜šŸ¬  The future of MySQL is Postgres   šŸ˜
šŸ¬ The future of MySQL is Postgres šŸ˜RTylerCroy
Ā 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
Ā 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
Ā 
WhatsApp 9892124323 āœ“Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 āœ“Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 āœ“Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 āœ“Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
Ā 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGSujit Pal
Ā 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
Ā 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
Ā 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
Ā 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
Ā 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
Ā 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
Ā 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
Ā 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
Ā 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
Ā 
Finology Group ā€“ Insurtech Innovation Award 2024
Finology Group ā€“ Insurtech Innovation Award 2024Finology Group ā€“ Insurtech Innovation Award 2024
Finology Group ā€“ Insurtech Innovation Award 2024The Digital Insurer
Ā 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
Ā 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
Ā 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
Ā 

Recently uploaded (20)

04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
Ā 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
Ā 
šŸ¬ The future of MySQL is Postgres šŸ˜
šŸ¬  The future of MySQL is Postgres   šŸ˜šŸ¬  The future of MySQL is Postgres   šŸ˜
šŸ¬ The future of MySQL is Postgres šŸ˜
Ā 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
Ā 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
Ā 
WhatsApp 9892124323 āœ“Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 āœ“Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 āœ“Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 āœ“Call Girls In Kalyan ( Mumbai ) secure service
Ā 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAG
Ā 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
Ā 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
Ā 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Ā 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
Ā 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
Ā 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Ā 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
Ā 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
Ā 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
Ā 
Finology Group ā€“ Insurtech Innovation Award 2024
Finology Group ā€“ Insurtech Innovation Award 2024Finology Group ā€“ Insurtech Innovation Award 2024
Finology Group ā€“ Insurtech Innovation Award 2024
Ā 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
Ā 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Ā 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
Ā 

Simpler Core Data with RubyMotion

  • 1. Simpler Core Data with RubyMotion StefĆ”n Haļ¬‚iĆ°ason http://stefan.haļ¬‚idason.com @styrmis
  • 2. Why RubyMotion? ā€¢ Promises increased developer productivity ā€¢ Brings the ļ¬‚exibility of Ruby to iOS and OSX development ā€¢ Bridges directly to Obj-C libraries: no intermediate glue code ā€¢ A REPL for working with your app live! ā€¢ Make tweaks quickly ā€¢ Build whole views programmatically on the ļ¬‚y
  • 3. Why Core Data? ā€¢ Optimised for low-memory/embedded (iOS) devices ā€¢ Mature data access/persistence framework ā€¢ Also available on OSX ā€¢ Works with iCloudā€”free cloud syncing for your app
  • 4. Core Data is Difļ¬cult ā€¢ Provided boilerplate code unnecessarily complex ā€¢ An object graph thatā€™s persisted to an SQLite database ā€¢ Suggests relational access, which is not quite the case ā€¢ Typical patterns for working with relational data are not optimal here
  • 5. RubyMotion is ā€œEasyā€ ā€¢ Friendliness of Ruby ā€¢ An ARC equivalent is included ā€¢ Lots of work done to abstract complexity away ā€¢ More concepts similar to other OO languages
  • 6. Core Data and RubyMotion ā€¢ No equivalent of Xcodeā€™s visual data modeller ā€¢ How do I deļ¬ne my data model?! ā€¢ What about versioning?! ā€¢ How will I handle migrations?
  • 7. What we need ā€¢ Our data model (NSEntityDescriptions + NSRelationshipDescriptions forming our NSManagedObject) ā€¢ A Core Data Stack (NSManagedObjectModel + NSPersistentStoreCoordinator + NSManagedObjectContext) ā€¢ A workļ¬‚ow for versioning and migrating between versions
  • 8. Deļ¬ning Our Data Model ā€¢ We would normally do this in Xcode ā€¢ Visual Editor for .xcdatamodel bundles ā€¢ Integrated handling of versioning and custom migration code ā€¢ Automatic lightweight (schema) migrations ā€¢ How do we achieve this with RubyMotion?
  • 9. Options for RubyMotion ā€¢ Handle everything programmatically (low level) ā€¢ Use Xcode to work with .xcdatamodel ļ¬les, copy in each time ā€¢ Use a Ruby library for creating .xcdatamodel ļ¬les
  • 10. Handling Everything Programmatically entity = NSEntityDescription.alloc.init entity.name = 'Task' entity.managedObjectClassName = 'Task' entity.properties = [ 'task_description', NSStringAttributeType, 'completed', NSBooleanAttributeType ].each_slice(2).map do |name, type| property = NSAttributeDescription.alloc.init property.name = name property.attributeType = type property.optional = false property end
  • 11. Handling Everything Programmatically entity = NSEntityDescription.alloc.init entity.name = 'Task' entity.managedObjectClassName = 'Task' entity.properties = [ 'task_description', NSStringAttributeType, 'completed', NSBooleanAttributeType ].each_slice(2).map do |name, type| property = NSAttributeDescription.alloc.init property.name = name property.attributeType = type property.optional = false property end Not all that bad, but we want to use .xcdatamodel ļ¬les
  • 12. .xcdatamodel ļ¬les are just XML <?xml version="1.0" encoding="UTF-8" standalone="yes"?>! <model name="" userDefinedModelVersionIdentifier="001" type="com.apple.IDECoreDataModeler.DataModel" documentVersion="1.0" lastSavedToolsVersion="2061" systemVersion="12D78" minimumToolsVersion="Xcode 4.3" macOSVersion="Automatic" iOSVersion="Automatic">! <entity name="Article" syncable="YES">! <attribute name="title" optional="YES" attributeType="String" syncable="YES"/>! <relationship name="author" optional="YES" minCount="1" maxCount="1" deletionRule="Nullify" destinationEntity="Author" inverseName="articles" inverseEntity="Article" syncable="YES"/>! </entity>! <entity name="Author" syncable="YES">! <attribute name="name" optional="YES" attributeType="String" syncable="YES"/>! <relationship name="articles" optional="YES" minCount="1" maxCount="1" deletionRule="Nullify" destinationEntity="Article" inverseName="author" inverseEntity="Author" syncable="YES"/>! </entity>! </model>
  • 13. Using a library to generate .xcdatamodel ļ¬les (ruby-xcdm) 1 schema "001" do! 2 entity "Article" do! 3 string :body, optional: false! 4 integer32 :length! 5 boolean :published, default: false! 6 datetime :publishedAt, default: false! 7 string :title, optional: false! 8 ! 9 belongs_to :author! 10 end! 11 ! 12 entity "Author" do! 13 float :fee! 14 string :name, optional: false! 15 has_many :articles! 16 end! 17 end
  • 14. Workļ¬‚ow ā€¢ Create schema ļ¬le in schemas directory, e.g. schemas/001_initial.rb ā€¢ Build the schema ā€¢ Add a new schema version, e.g. 002_add_new_fields.rb ā€¢ Rebuild the schema ā€¢ Thatā€™s it!
  • 15. Workļ¬‚ow $ echo "gem 'ruby-xcdm', '0.0.5'" >> Gemfile $ bundle install $ rake schema:build Generating Data Model learn-xcdm Loading schemas/001_initial.rb Writing resources/learn-xcdm.xcdatamodeld/1.xcdatamodel/ contents $ rake # The default rake task is to run the app in the simulator (main)> mom = NSManagedObjectModel.mergedModelFromBundles(nil) => #<NSManagedObjectModel:0x8fa7690> (main)> mom.entities.count => 2 (main)> mom.entities.first.name => "Article" (main)> mom.entities.first.propertiesByName => {"body"=>#<NSAttributeDescription:0x8e5db30>, "title"=>#<NSAttributeDescription:0x8ea4770>}
  • 16. Advantages of using ruby- xcdm ā€¢ No magic: generates XML from a schema ā€¢ Schema versions are fully text-based and readable, making them well-suited to version control ā€¢ Can compile our versions into .xcdatamodeld bundles, completely removing dependence on Xcode
  • 17. Basic Core Data Stack 1 model = NSManagedObjectModel.mergedModelFromBundles(nil) 2 3 store = NSPersistentStoreCoordinator.alloc.initWithManagedObjectModel(model) 4 store_path = File.join(NSHomeDirectory(), 'Documents', 'LearnXcdm.sqlite') 5 store_url = NSURL.fileURLWithPath(store_path) 6 7 options = { NSMigratePersistentStoresAutomaticallyOption => true, 8 NSInferMappingModelAutomaticallyOption => true } 9 10 error_ptr = Pointer.new(:object) 11 12 unless store.addPersistentStoreWithType(NSSQLiteStoreType, 13 configuration: nil, 14 URL: store_url, 15 options: options, 16 error: error_ptr) 17 raise "[ERROR] Failed to create persistent store: #{error_ptr[0].description}" 18 end 19 20 @context = NSManagedObjectContext.alloc.init 21 @context.persistentStoreCoordinator = store
  • 18. Core Data Query ā€¢ From the developers of ruby-xcdm ā€¢ Abstracts away much of the complexity of Core Data ā€¢ All you need is your .xcdatamodeld bundle
  • 19. Core Data Query in Action # app/models/task.rb class Task < CDQManagedObject end ! # app/app_delegate.rb class AppDelegate include CDQ ! def application(application, didFinishLaunchingWithOptions:launchOptions) cdq.setup true end end
  • 20. Core Data Query in Action (main)> Task.count => 0 (main)> t1 = Task.create(task_description: "Complete presentation") (main)> t2 = Task.create(task_description: "File tax return") (main)> cdq.save => true (main)> exit $ rake ... (main)> Task.count => 2 (main)> t1, t2 = Task.all.array (main)> t1.task_description => "Complete chapter" (main)> t2.task_description => "File tax return" (main)> t2.destroy => #<NSManagedObjectContext:0x914cbe0> (main)> cdq.save => true (main)> Task.count => 1
  • 21. Core Data in Action Author.where(:name).eq("Emily") Author.where(:name).not_equal("Emily") Author.limit(1) Author.offset(10) Author.where(:name).contains("A").offset(10).first ! # Conjuctions Author.where(:name).contains("Emily").and.contains("Dickinson") Author.where(:name).starts_with("E").or(:pub_count).eq(1) ! # Nested Conjuctions Author.where(:name).contains("Emily").and(cdq(:pub_count).gt(100).or.lt(10) ) ! # Relationships Author.first.publications.offset(2).limit(1) cdq(emily_dickinson).publications.where(:type).eq('poetry') ! class Author < CDQManagedObject scope :prolific, where(:pub_count).gt(50) end
  • 22. Takeaways ā€¢ Donā€™t be put off by the Xcode boilerplate: Core Data doesnā€™t have to be that hard ā€¢ With CDQ, Core Data is arguably easier to use with RubyMotion rather than harder ā€¢ XCDM, CDQ and RubyMotion Query (all by Inļ¬nitered) are all worth taking a look at
  • 23. Next Steps ā€¢ In the coming weeks Iā€™ll be researching and writing about: ā€¢ How to best handle heavyweight/data migrations in RubyMotion ā€¢ Deconstructing the ā€˜magicā€™ in Core Data Query ā€¢ RubyMotion development best practices StefĆ”n Haļ¬‚iĆ°ason http://stefan.haļ¬‚idason.com @styrmis