SlideShare a Scribd company logo
1 of 66
Download to read offline
Diego Freniche / @dfreniche / http://www.freniche.com
Core Data Workshop
Diego Freniche: programmer & teacher
Diego Freniche: programmer & teacher
• @dfreniche
• Freelance Mobile developer: iOS/Android/BB10/
webOS/...
• In a former life Java Certifications Collector: SCJP
1.5, SCJP 1.6, SCWCD 1.5, SCBCD 1.3
• Some languages: BASIC, PASCAL, C, C++, Delphi,
COBOL, Clipper, Visual Basic, Java, JavaScript,
Objective-C
Hello, World!
Before we start...
Before we start...
• Switch OFF phones
Before we start...
• Switch OFF phones
• Been here is funny
Before we start...
• Switch OFF phones
• Been here is funny
• ¡Live the moment!¡Carpe diem!
Before we start...
• Switch OFF phones
• Been here is funny
• ¡Live the moment!¡Carpe diem!
• Ask me a lot. Don’t yawn
What you need (checklist)
• a Mac with OS X capable of running Xcode 4.6.1
• last Xcode 4 installed 4.6.1
• You can also use prerelease software, if you are a registered Apple developer.
No support then, sorry :-D
• SimPholders installed: http://simpholders.com
• SQLLite database browser: http://sqlitebrowser.sourceforge.net
• (optional) set $HOME/Library folder visible, using (from a Terminal)
Diego Freniche / http://www.freniche.com
Idea: Creating the Core Data Stack
Diego Freniche / @dfreniche / http://www.freniche.com
The Core Data Stack
Managed Object Context
Persistent Store Coordinator
Persistent Object Store
Managed Object Model
Diego Freniche / @dfreniche / http://www.freniche.com
Doubts
Diego Freniche / @dfreniche / http://www.freniche.com
Doubts
• Use Apple’s code?
Diego Freniche / @dfreniche / http://www.freniche.com
Doubts
• Use Apple’s code?
• Really?
Diego Freniche / @dfreniche / http://www.freniche.com
Doubts
• Use Apple’s code?
• Really?
• Use a singleton?
Diego Freniche / @dfreniche / http://www.freniche.com
Doubts
• Use Apple’s code?
• Really?
• Use a singleton?
• Don’t use a singleton?
Diego Freniche / @dfreniche / http://www.freniche.com
Doubts
• Use Apple’s code?
• Really?
• Use a singleton?
• Don’t use a singleton?
• Use dependency injection?
Diego Freniche / @dfreniche / http://www.freniche.com
Apple’s code
Diego Freniche / @dfreniche / http://www.freniche.com
Apple’s code
- (void)saveContext
{
NSError *error = nil;
NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
if (managedObjectContext != nil) {
if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
}
}
#pragma mark - Core Data stack
// Returns the managed object context for the application.
// If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application.
- (NSManagedObjectContext *)managedObjectContext
{
if (_managedObjectContext != nil) {
return _managedObjectContext;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil) {
_managedObjectContext = [[NSManagedObjectContext alloc] init];
[_managedObjectContext setPersistentStoreCoordinator:coordinator];
}
return _managedObjectContext;
}
// Returns the managed object model for the application.
// If the model doesn't already exist, it is created from the application's model.
- (NSManagedObjectModel *)managedObjectModel
{
if (_managedObjectModel != nil) {
return _managedObjectModel;
}
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"Test" withExtension:@"momd"];
_managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return _managedObjectModel;
}
// Returns the persistent store coordinator for the application.
// If the coordinator doesn't already exist, it is created and the application's store added to it.
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
if (_persistentStoreCoordinator != nil) {
return _persistentStoreCoordinator;
}
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"Test.sqlite"];
NSError *error = nil;
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
/*
Replace this implementation with code to handle the error appropriately.
abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
Typical reasons for an error here include:
* The persistent store is not accessible;
* The schema for the persistent store is incompatible with current managed object model.
Check the error message to determine what the actual problem was.
If the persistent store is not accessible, there is typically something wrong with the file path. Often, a file URL is pointing into the application's resources directory instead of a writeable directory.
If you encounter schema incompatibility errors during development, you can reduce their frequency by:
* Simply deleting the existing store:
[[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil]
* Performing automatic lightweight migration by passing the following dictionary as the options parameter:
@{NSMigratePersistentStoresAutomaticallyOption:@YES, NSInferMappingModelAutomaticallyOption:@YES}
Lightweight migration will only work for a limited set of schema changes; consult "Core Data Model Versioning and Data Migration Programming Guide" for details.
*/
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
return _persistentStoreCoordinator;
}
#pragma mark - Application's Documents directory
// Returns the URL to the application's Documents directory.
- (NSURL *)applicationDocumentsDirectory
{
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
Diego Freniche / @dfreniche / http://www.freniche.com
Apple’s code problems
• Core Data Stack inside AppDelegate?
• Really?
• Separation of concerns?
• Only one Managed Object Context
Diego Freniche / @dfreniche / http://www.freniche.com
Create our own Core Data Stack
Diego Freniche / @dfreniche / http://www.freniche.com
Create our own Core Data Stack
• In one “simple” method
Diego Freniche / @dfreniche / http://www.freniche.com
Create our own Core Data Stack
• In one “simple” method
• Singleton / not singleton?
Diego Freniche / @dfreniche / http://www.freniche.com
Create our own Core Data Stack
• In one “simple” method
• Singleton / not singleton?
• Use both!
Diego Freniche / @dfreniche / http://www.freniche.com
Dependency injection? Or singletons FTW?
• It depends :-)
Diego Freniche / http://www.freniche.com
Idea: using asserts to check threads
Diego Freniche / http://www.freniche.com
Asserts
• Check if we are running UI code in the UI Thread
• Check if we are NOT running Core Data code in the UI Thread
Diego Freniche / http://www.freniche.com
Asserts
• Check if we are running UI code in the UI Thread
• Check if we are NOT running Core Data code in the UI Thread
#define DF_ASSERT_MAIN_THREAD [NSThread isMainThread]?:(NSLog(@"NOT IN MAIN
THREAD"),abort())
Diego Freniche / http://www.freniche.com
Idea: create a common UITableView/Core data
class
Diego Freniche / http://www.freniche.com
Idea: use an NSManagedObject subclass
Diego Freniche / @dfreniche / http://www.freniche.com
Entities Design Tips
Diego Freniche / @dfreniche / http://www.freniche.com
Entities Design Tips
• Always add field order
Diego Freniche / @dfreniche / http://www.freniche.com
Entities Design Tips
• Always add field order
• Try to create a good UML diagram at first
Diego Freniche / @dfreniche / http://www.freniche.com
Entities Design Tips
• Always add field order
• Try to create a good UML diagram at first
• Have an NSString constant with every Entity’s name inside .h
Diego Freniche / @dfreniche / http://www.freniche.com
Extend NSManagedObject
• Editor > Create NSManagedObject subclass...
• creates @dynamic properties
• getter / setter generated in runtime (@property in compile time)
• Core Data doesn’t know at compile time if the persistent store is going to
be XML or a DB (or in-memory)
Diego Freniche / @dfreniche / http://www.freniche.com
Extend NSManagedObject
• overwrite init to call designated initializer
Diego Freniche / @dfreniche / http://www.freniche.com
Extend NSManagedObject
• overwrite init to call designated initializer
-(id)init {
NSManagedObjectContext *context = [[CoreDataStack coreDataStack]
managedObjectContext];
return [self initWithEntity:[NSEntityDescription
entityForName:kRETROITEM_ENTITY inManagedObjectContext:context ]
insertIntoManagedObjectContext:context];
}
Diego Freniche / @dfreniche / http://www.freniche.com
Validate Properties
• One for every property, if we want it
• Passing parameter by reference
• It should return YES if validation is passed
Diego Freniche / @dfreniche / http://www.freniche.com
Validate Properties
• One for every property, if we want it
• Passing parameter by reference
• It should return YES if validation is passed
-(BOOL)validateName:(id *)ioValue error:(NSError * __autoreleasing *)outError;
Diego Freniche / @dfreniche / http://www.freniche.com
Validator for operations
• First thing: must call [super ...]
• Useful to check business rules (using several properties)
Diego Freniche / @dfreniche / http://www.freniche.com
Validator for operations
• First thing: must call [super ...]
• Useful to check business rules (using several properties)
- (BOOL)validateForDelete:(NSError **)error
- (BOOL)validateForInsert:(NSError **)error
- (BOOL)validateForUpdate:(NSError **)error
Diego Freniche / @dfreniche / http://www.freniche.com
Support for KVO
• Good for Faults
Diego Freniche / @dfreniche / http://www.freniche.com
Support for KVO
• Good for Faults
- (void)willAccessValueForKey:(NSString *)key
Diego Freniche / http://www.freniche.com
Idea: use Mogenerator
Diego Freniche / @dfreniche / http://www.freniche.com
Mogenerator
created by Jonathan 'Wolf' Rentzsch
Diego Freniche / @dfreniche / http://www.freniche.com
Mogenerator (quoting from the web page)
Diego Freniche / @dfreniche / http://www.freniche.com
Mogenerator (quoting from the web page)
• http://rentzsch.github.io/mogenerator/
Diego Freniche / @dfreniche / http://www.freniche.com
Mogenerator (quoting from the web page)
• http://rentzsch.github.io/mogenerator/
• generates Objective-C code for your Core Data custom classes
Diego Freniche / @dfreniche / http://www.freniche.com
Mogenerator (quoting from the web page)
• http://rentzsch.github.io/mogenerator/
• generates Objective-C code for your Core Data custom classes
• Unlike Xcode, mogenerator manages two classes per entity: one for
machines, one for humans
Diego Freniche / @dfreniche / http://www.freniche.com
Mogenerator (quoting from the web page)
• http://rentzsch.github.io/mogenerator/
• generates Objective-C code for your Core Data custom classes
• Unlike Xcode, mogenerator manages two classes per entity: one for
machines, one for humans
• The machine class can always be overwritten to match the data model,
with humans’ work effortlessly preserved
Diego Freniche / @dfreniche / http://www.freniche.com
Installing mogenerator
Diego Freniche / @dfreniche / http://www.freniche.com
Using it
• it’s a script, so we can launch it from command line
• using iTerm, DTerm, etc.
• Best way: to have it inside our project
• Create a new Aggregate Target (New Target > Other > Aggregate)
• Add Build Phase > Add Run Script
Diego Freniche / @dfreniche / http://www.freniche.com
Using it
• it’s a script, so we can launch it from command line
• using iTerm, DTerm, etc.
• Best way: to have it inside our project
• Create a new Aggregate Target (New Target > Other > Aggregate)
• Add Build Phase > Add Run Script
mogenerator --template-var arc=true -m RetroStuffTracker/
RetroStuffTracker.xcdatamodeld/RetroStuffTracker.xcdatamodel/
Diego Freniche / @dfreniche / http://www.freniche.com
Two classes
• _MyClass.*: machine generated
• *MyClass.*: human edited
• Never, ever recreate the classes
again from the Core Data Model
Diego Freniche / @dfreniche / http://www.freniche.com
Two classes
• _MyClass.*: machine generated
• *MyClass.*: human edited
• Never, ever recreate the classes
again from the Core Data Model
Diego Freniche / http://www.freniche.com
Two classes
Diego Freniche / http://www.freniche.com
#import "_RetroItem.h"
@interface RetroItem : _RetroItem {}
// Custom logic goes here.
@end
Two classes
Diego Freniche / http://www.freniche.com
#import "_RetroItem.h"
@interface RetroItem : _RetroItem {}
// Custom logic goes here.
@end
#import "RetroItem.h"
@interface RetroItem ()
// Private interface goes here.
@end
@implementation RetroItem
// Custom logic goes here.
@end
Two classes
Diego Freniche / http://www.freniche.com
Idea: use Magical Record
Diego Freniche / http://www.freniche.com
Magical record != avoid Core Data at all costs
Diego Freniche / http://www.freniche.com
Magical record != avoid Core Data at all costs
• Just a bunch of categories to help you write less code
Diego Freniche / http://www.freniche.com
Magical record != avoid Core Data at all costs
• Just a bunch of categories to help you write less code
• You have to know your sh*t
Diego Freniche / http://www.freniche.com
Magical record != avoid Core Data at all costs
• Just a bunch of categories to help you write less code
• You have to know your sh*t
• CocoaPods friendly
Diego Freniche / http://www.freniche.com
Magical record != avoid Core Data at all costs
• Just a bunch of categories to help you write less code
• You have to know your sh*t
• CocoaPods friendly
• Ideal: use Unit testing + Mogenerator + CocoaPods + Magical Record
Diego Freniche / http://www.freniche.com
Magical record != avoid Core Data at all costs
• Just a bunch of categories to help you write less code
• You have to know your sh*t
• CocoaPods friendly
• Ideal: use Unit testing + Mogenerator + CocoaPods + Magical Record
• My point: 7 people, 7 ideas, all great
Diego Freniche / http://www.freniche.com
Magical record != avoid Core Data at all costs
• Just a bunch of categories to help you write less code
• You have to know your sh*t
• CocoaPods friendly
• Ideal: use Unit testing + Mogenerator + CocoaPods + Magical Record
• My point: 7 people, 7 ideas, all great
• all different

More Related Content

What's hot

Android | Busy Java Developers Guide to Android: UI | Ted Neward
Android | Busy Java Developers Guide to Android: UI | Ted NewardAndroid | Busy Java Developers Guide to Android: UI | Ted Neward
Android | Busy Java Developers Guide to Android: UI | Ted NewardJAX London
 
Being Dangerous with Twig
Being Dangerous with TwigBeing Dangerous with Twig
Being Dangerous with TwigRyan Weaver
 
Writing great documentation - CodeConf 2011
Writing great documentation - CodeConf 2011Writing great documentation - CodeConf 2011
Writing great documentation - CodeConf 2011Jacob Kaplan-Moss
 
Killing the Angle Bracket
Killing the Angle BracketKilling the Angle Bracket
Killing the Angle Bracketjnewmanux
 
Twig for Drupal 8 and PHP | Presented at OC Drupal
Twig for Drupal 8 and PHP | Presented at OC DrupalTwig for Drupal 8 and PHP | Presented at OC Drupal
Twig for Drupal 8 and PHP | Presented at OC Drupalwebbywe
 
Html 5 in a big nutshell
Html 5 in a big nutshellHtml 5 in a big nutshell
Html 5 in a big nutshellLennart Schoors
 
Virtues of platform development
Virtues of platform developmentVirtues of platform development
Virtues of platform developmentPhillip Jackson
 
The DOM is a Mess @ Yahoo
The DOM is a Mess @ YahooThe DOM is a Mess @ Yahoo
The DOM is a Mess @ Yahoojeresig
 
From YUI3 to K2
From YUI3 to K2From YUI3 to K2
From YUI3 to K2kaven yan
 
Web Development with Python and Django
Web Development with Python and DjangoWeb Development with Python and Django
Web Development with Python and DjangoMichael Pirnat
 
PyGrunn 2017 - Django Performance Unchained - slides
PyGrunn 2017 - Django Performance Unchained - slidesPyGrunn 2017 - Django Performance Unchained - slides
PyGrunn 2017 - Django Performance Unchained - slidesArtur Barseghyan
 
Developing Complex WordPress Sites without Fear of Failure (with MVC)
Developing Complex WordPress Sites without Fear of Failure (with MVC)Developing Complex WordPress Sites without Fear of Failure (with MVC)
Developing Complex WordPress Sites without Fear of Failure (with MVC)Mike Schinkel
 
Hybrid Web Applications
Hybrid Web ApplicationsHybrid Web Applications
Hybrid Web ApplicationsJames Da Costa
 
Introduction to node.js by Ran Mizrahi @ Reversim Summit
Introduction to node.js by Ran Mizrahi @ Reversim SummitIntroduction to node.js by Ran Mizrahi @ Reversim Summit
Introduction to node.js by Ran Mizrahi @ Reversim SummitRan Mizrahi
 
Writing Software not Code with Cucumber
Writing Software not Code with CucumberWriting Software not Code with Cucumber
Writing Software not Code with CucumberBen Mabey
 

What's hot (20)

Javascript Best Practices
Javascript Best PracticesJavascript Best Practices
Javascript Best Practices
 
Android | Busy Java Developers Guide to Android: UI | Ted Neward
Android | Busy Java Developers Guide to Android: UI | Ted NewardAndroid | Busy Java Developers Guide to Android: UI | Ted Neward
Android | Busy Java Developers Guide to Android: UI | Ted Neward
 
Being Dangerous with Twig
Being Dangerous with TwigBeing Dangerous with Twig
Being Dangerous with Twig
 
Writing great documentation - CodeConf 2011
Writing great documentation - CodeConf 2011Writing great documentation - CodeConf 2011
Writing great documentation - CodeConf 2011
 
Killing the Angle Bracket
Killing the Angle BracketKilling the Angle Bracket
Killing the Angle Bracket
 
Metaprogramming with javascript
Metaprogramming with javascriptMetaprogramming with javascript
Metaprogramming with javascript
 
Twig for Drupal 8 and PHP | Presented at OC Drupal
Twig for Drupal 8 and PHP | Presented at OC DrupalTwig for Drupal 8 and PHP | Presented at OC Drupal
Twig for Drupal 8 and PHP | Presented at OC Drupal
 
Html 5 in a big nutshell
Html 5 in a big nutshellHtml 5 in a big nutshell
Html 5 in a big nutshell
 
All of Javascript
All of JavascriptAll of Javascript
All of Javascript
 
Welcome to hack
Welcome to hackWelcome to hack
Welcome to hack
 
Php simple
Php simplePhp simple
Php simple
 
Virtues of platform development
Virtues of platform developmentVirtues of platform development
Virtues of platform development
 
The DOM is a Mess @ Yahoo
The DOM is a Mess @ YahooThe DOM is a Mess @ Yahoo
The DOM is a Mess @ Yahoo
 
From YUI3 to K2
From YUI3 to K2From YUI3 to K2
From YUI3 to K2
 
Web Development with Python and Django
Web Development with Python and DjangoWeb Development with Python and Django
Web Development with Python and Django
 
PyGrunn 2017 - Django Performance Unchained - slides
PyGrunn 2017 - Django Performance Unchained - slidesPyGrunn 2017 - Django Performance Unchained - slides
PyGrunn 2017 - Django Performance Unchained - slides
 
Developing Complex WordPress Sites without Fear of Failure (with MVC)
Developing Complex WordPress Sites without Fear of Failure (with MVC)Developing Complex WordPress Sites without Fear of Failure (with MVC)
Developing Complex WordPress Sites without Fear of Failure (with MVC)
 
Hybrid Web Applications
Hybrid Web ApplicationsHybrid Web Applications
Hybrid Web Applications
 
Introduction to node.js by Ran Mizrahi @ Reversim Summit
Introduction to node.js by Ran Mizrahi @ Reversim SummitIntroduction to node.js by Ran Mizrahi @ Reversim Summit
Introduction to node.js by Ran Mizrahi @ Reversim Summit
 
Writing Software not Code with Cucumber
Writing Software not Code with CucumberWriting Software not Code with Cucumber
Writing Software not Code with Cucumber
 

Similar to Core data intermediate Workshop at NSSpain 2013

Core data WIPJam workshop @ MWC'14
Core data WIPJam workshop @ MWC'14Core data WIPJam workshop @ MWC'14
Core data WIPJam workshop @ MWC'14Diego Freniche Brito
 
Beyond Fluffy Bunny. How I leveraged WebObjects in my lean startup.
Beyond Fluffy Bunny. How I leveraged WebObjects in my lean startup.Beyond Fluffy Bunny. How I leveraged WebObjects in my lean startup.
Beyond Fluffy Bunny. How I leveraged WebObjects in my lean startup.WO Community
 
SharePoint Development 101
SharePoint Development 101SharePoint Development 101
SharePoint Development 101Greg Hurlman
 
Stencil: The Time for Vanilla Web Components has Arrived
Stencil: The Time for Vanilla Web Components has ArrivedStencil: The Time for Vanilla Web Components has Arrived
Stencil: The Time for Vanilla Web Components has ArrivedGil Fink
 
SharePoint Framework, Angular and Azure Functions
SharePoint Framework, Angular and Azure FunctionsSharePoint Framework, Angular and Azure Functions
SharePoint Framework, Angular and Azure FunctionsSébastien Levert
 
Stencil the time for vanilla web components has arrived
Stencil the time for vanilla web components has arrivedStencil the time for vanilla web components has arrived
Stencil the time for vanilla web components has arrivedGil Fink
 
CoreData - there is an ORM you can like!
CoreData - there is an ORM you can like!CoreData - there is an ORM you can like!
CoreData - there is an ORM you can like!Tomáš Jukin
 
Php on the Web and Desktop
Php on the Web and DesktopPhp on the Web and Desktop
Php on the Web and DesktopElizabeth Smith
 
Enterprise PHP (PHP London Conference 2008)
Enterprise PHP (PHP London Conference 2008)Enterprise PHP (PHP London Conference 2008)
Enterprise PHP (PHP London Conference 2008)Ivo Jansch
 
Code Coverage for Total Security in Application Migrations
Code Coverage for Total Security in Application MigrationsCode Coverage for Total Security in Application Migrations
Code Coverage for Total Security in Application MigrationsDana Luther
 
Browser Internals for JS Devs: WebU Toronto 2016 by Alex Blom
Browser Internals for JS Devs: WebU Toronto 2016 by Alex BlomBrowser Internals for JS Devs: WebU Toronto 2016 by Alex Blom
Browser Internals for JS Devs: WebU Toronto 2016 by Alex BlomAlex Blom
 

Similar to Core data intermediate Workshop at NSSpain 2013 (20)

Core data WIPJam workshop @ MWC'14
Core data WIPJam workshop @ MWC'14Core data WIPJam workshop @ MWC'14
Core data WIPJam workshop @ MWC'14
 
Beyond Fluffy Bunny. How I leveraged WebObjects in my lean startup.
Beyond Fluffy Bunny. How I leveraged WebObjects in my lean startup.Beyond Fluffy Bunny. How I leveraged WebObjects in my lean startup.
Beyond Fluffy Bunny. How I leveraged WebObjects in my lean startup.
 
React nativebeginner1
React nativebeginner1React nativebeginner1
React nativebeginner1
 
SharePoint Development 101
SharePoint Development 101SharePoint Development 101
SharePoint Development 101
 
Intro to appcelerator
Intro to appceleratorIntro to appcelerator
Intro to appcelerator
 
Continuous feature-development
Continuous feature-developmentContinuous feature-development
Continuous feature-development
 
Stencil: The Time for Vanilla Web Components has Arrived
Stencil: The Time for Vanilla Web Components has ArrivedStencil: The Time for Vanilla Web Components has Arrived
Stencil: The Time for Vanilla Web Components has Arrived
 
Mobile native-hacks
Mobile native-hacksMobile native-hacks
Mobile native-hacks
 
Lecture 2: ES6 / ES2015 Slide
Lecture 2: ES6 / ES2015 SlideLecture 2: ES6 / ES2015 Slide
Lecture 2: ES6 / ES2015 Slide
 
SharePoint Framework, Angular and Azure Functions
SharePoint Framework, Angular and Azure FunctionsSharePoint Framework, Angular and Azure Functions
SharePoint Framework, Angular and Azure Functions
 
Stencil the time for vanilla web components has arrived
Stencil the time for vanilla web components has arrivedStencil the time for vanilla web components has arrived
Stencil the time for vanilla web components has arrived
 
l2-es6-160830040119.pdf
l2-es6-160830040119.pdfl2-es6-160830040119.pdf
l2-es6-160830040119.pdf
 
CoreData - there is an ORM you can like!
CoreData - there is an ORM you can like!CoreData - there is an ORM you can like!
CoreData - there is an ORM you can like!
 
Php on the Web and Desktop
Php on the Web and DesktopPhp on the Web and Desktop
Php on the Web and Desktop
 
Enterprise PHP (PHP London Conference 2008)
Enterprise PHP (PHP London Conference 2008)Enterprise PHP (PHP London Conference 2008)
Enterprise PHP (PHP London Conference 2008)
 
Code Coverage for Total Security in Application Migrations
Code Coverage for Total Security in Application MigrationsCode Coverage for Total Security in Application Migrations
Code Coverage for Total Security in Application Migrations
 
Browser Internals for JS Devs: WebU Toronto 2016 by Alex Blom
Browser Internals for JS Devs: WebU Toronto 2016 by Alex BlomBrowser Internals for JS Devs: WebU Toronto 2016 by Alex Blom
Browser Internals for JS Devs: WebU Toronto 2016 by Alex Blom
 
tut0000021-hevery
tut0000021-heverytut0000021-hevery
tut0000021-hevery
 
tut0000021-hevery
tut0000021-heverytut0000021-hevery
tut0000021-hevery
 
Seven deadly theming sins
Seven deadly theming sinsSeven deadly theming sins
Seven deadly theming sins
 

More from Diego Freniche Brito

Los mejores consejos para migrar de RDBMS a MongoDB.pptx.pdf
Los mejores consejos para migrar de RDBMS a MongoDB.pptx.pdfLos mejores consejos para migrar de RDBMS a MongoDB.pptx.pdf
Los mejores consejos para migrar de RDBMS a MongoDB.pptx.pdfDiego Freniche Brito
 
From Mobile to MongoDB: Store your app's data using Realm
From Mobile to MongoDB: Store your app's data using RealmFrom Mobile to MongoDB: Store your app's data using Realm
From Mobile to MongoDB: Store your app's data using RealmDiego Freniche Brito
 
MobileConf 2021 Slides: Let's build macOS CLI Utilities using Swift
MobileConf 2021 Slides:  Let's build macOS CLI Utilities using SwiftMobileConf 2021 Slides:  Let's build macOS CLI Utilities using Swift
MobileConf 2021 Slides: Let's build macOS CLI Utilities using SwiftDiego Freniche Brito
 
Functional Programming for Busy Object Oriented Programmers
Functional Programming for Busy Object Oriented ProgrammersFunctional Programming for Busy Object Oriented Programmers
Functional Programming for Busy Object Oriented ProgrammersDiego Freniche Brito
 
Cocoa pods iOSDevUK 14 talk: managing your libraries
Cocoa pods iOSDevUK 14 talk: managing your librariesCocoa pods iOSDevUK 14 talk: managing your libraries
Cocoa pods iOSDevUK 14 talk: managing your librariesDiego Freniche Brito
 
Swift as a scripting language iOSDevUK14 Lightning talk
Swift as a scripting language iOSDevUK14 Lightning talkSwift as a scripting language iOSDevUK14 Lightning talk
Swift as a scripting language iOSDevUK14 Lightning talkDiego Freniche Brito
 
Charla XVII Beta Beers Sevilla: ¿Ágil? Como la rodilla de un click
Charla XVII Beta Beers Sevilla: ¿Ágil? Como la rodilla de un clickCharla XVII Beta Beers Sevilla: ¿Ágil? Como la rodilla de un click
Charla XVII Beta Beers Sevilla: ¿Ágil? Como la rodilla de un clickDiego Freniche Brito
 

More from Diego Freniche Brito (7)

Los mejores consejos para migrar de RDBMS a MongoDB.pptx.pdf
Los mejores consejos para migrar de RDBMS a MongoDB.pptx.pdfLos mejores consejos para migrar de RDBMS a MongoDB.pptx.pdf
Los mejores consejos para migrar de RDBMS a MongoDB.pptx.pdf
 
From Mobile to MongoDB: Store your app's data using Realm
From Mobile to MongoDB: Store your app's data using RealmFrom Mobile to MongoDB: Store your app's data using Realm
From Mobile to MongoDB: Store your app's data using Realm
 
MobileConf 2021 Slides: Let's build macOS CLI Utilities using Swift
MobileConf 2021 Slides:  Let's build macOS CLI Utilities using SwiftMobileConf 2021 Slides:  Let's build macOS CLI Utilities using Swift
MobileConf 2021 Slides: Let's build macOS CLI Utilities using Swift
 
Functional Programming for Busy Object Oriented Programmers
Functional Programming for Busy Object Oriented ProgrammersFunctional Programming for Busy Object Oriented Programmers
Functional Programming for Busy Object Oriented Programmers
 
Cocoa pods iOSDevUK 14 talk: managing your libraries
Cocoa pods iOSDevUK 14 talk: managing your librariesCocoa pods iOSDevUK 14 talk: managing your libraries
Cocoa pods iOSDevUK 14 talk: managing your libraries
 
Swift as a scripting language iOSDevUK14 Lightning talk
Swift as a scripting language iOSDevUK14 Lightning talkSwift as a scripting language iOSDevUK14 Lightning talk
Swift as a scripting language iOSDevUK14 Lightning talk
 
Charla XVII Beta Beers Sevilla: ¿Ágil? Como la rodilla de un click
Charla XVII Beta Beers Sevilla: ¿Ágil? Como la rodilla de un clickCharla XVII Beta Beers Sevilla: ¿Ágil? Como la rodilla de un click
Charla XVII Beta Beers Sevilla: ¿Ágil? Como la rodilla de un click
 

Recently uploaded

Quantum Leap in Next-Generation Computing
Quantum Leap in Next-Generation ComputingQuantum Leap in Next-Generation Computing
Quantum Leap in Next-Generation ComputingWSO2
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
Design Guidelines for Passkeys 2024.pptx
Design Guidelines for Passkeys 2024.pptxDesign Guidelines for Passkeys 2024.pptx
Design Guidelines for Passkeys 2024.pptxFIDO Alliance
 
Design and Development of a Provenance Capture Platform for Data Science
Design and Development of a Provenance Capture Platform for Data ScienceDesign and Development of a Provenance Capture Platform for Data Science
Design and Development of a Provenance Capture Platform for Data SciencePaolo Missier
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
Hyatt driving innovation and exceptional customer experiences with FIDO passw...
Hyatt driving innovation and exceptional customer experiences with FIDO passw...Hyatt driving innovation and exceptional customer experiences with FIDO passw...
Hyatt driving innovation and exceptional customer experiences with FIDO passw...FIDO Alliance
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Decarbonising Commercial Real Estate: The Role of Operational Performance
Decarbonising Commercial Real Estate: The Role of Operational PerformanceDecarbonising Commercial Real Estate: The Role of Operational Performance
Decarbonising Commercial Real Estate: The Role of Operational PerformanceIES VE
 
2024 May Patch Tuesday
2024 May Patch Tuesday2024 May Patch Tuesday
2024 May Patch TuesdayIvanti
 
WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024Lorenzo Miniero
 
ADP Passwordless Journey Case Study.pptx
ADP Passwordless Journey Case Study.pptxADP Passwordless Journey Case Study.pptx
ADP Passwordless Journey Case Study.pptxFIDO Alliance
 
Introduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMIntroduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMKumar Satyam
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
Navigating Identity and Access Management in the Modern Enterprise
Navigating Identity and Access Management in the Modern EnterpriseNavigating Identity and Access Management in the Modern Enterprise
Navigating Identity and Access Management in the Modern EnterpriseWSO2
 
Portal Kombat : extension du réseau de propagande russe
Portal Kombat : extension du réseau de propagande russePortal Kombat : extension du réseau de propagande russe
Portal Kombat : extension du réseau de propagande russe中 央社
 
Modernizing Legacy Systems Using Ballerina
Modernizing Legacy Systems Using BallerinaModernizing Legacy Systems Using Ballerina
Modernizing Legacy Systems Using BallerinaWSO2
 
The Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and InsightThe Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and InsightSafe Software
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
Continuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
Continuing Bonds Through AI: A Hermeneutic Reflection on ThanabotsContinuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
Continuing Bonds Through AI: A Hermeneutic Reflection on ThanabotsLeah Henrickson
 

Recently uploaded (20)

Quantum Leap in Next-Generation Computing
Quantum Leap in Next-Generation ComputingQuantum Leap in Next-Generation Computing
Quantum Leap in Next-Generation Computing
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Design Guidelines for Passkeys 2024.pptx
Design Guidelines for Passkeys 2024.pptxDesign Guidelines for Passkeys 2024.pptx
Design Guidelines for Passkeys 2024.pptx
 
Design and Development of a Provenance Capture Platform for Data Science
Design and Development of a Provenance Capture Platform for Data ScienceDesign and Development of a Provenance Capture Platform for Data Science
Design and Development of a Provenance Capture Platform for Data Science
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Hyatt driving innovation and exceptional customer experiences with FIDO passw...
Hyatt driving innovation and exceptional customer experiences with FIDO passw...Hyatt driving innovation and exceptional customer experiences with FIDO passw...
Hyatt driving innovation and exceptional customer experiences with FIDO passw...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Decarbonising Commercial Real Estate: The Role of Operational Performance
Decarbonising Commercial Real Estate: The Role of Operational PerformanceDecarbonising Commercial Real Estate: The Role of Operational Performance
Decarbonising Commercial Real Estate: The Role of Operational Performance
 
2024 May Patch Tuesday
2024 May Patch Tuesday2024 May Patch Tuesday
2024 May Patch Tuesday
 
WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024
 
ADP Passwordless Journey Case Study.pptx
ADP Passwordless Journey Case Study.pptxADP Passwordless Journey Case Study.pptx
ADP Passwordless Journey Case Study.pptx
 
Introduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMIntroduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDM
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Navigating Identity and Access Management in the Modern Enterprise
Navigating Identity and Access Management in the Modern EnterpriseNavigating Identity and Access Management in the Modern Enterprise
Navigating Identity and Access Management in the Modern Enterprise
 
Portal Kombat : extension du réseau de propagande russe
Portal Kombat : extension du réseau de propagande russePortal Kombat : extension du réseau de propagande russe
Portal Kombat : extension du réseau de propagande russe
 
Modernizing Legacy Systems Using Ballerina
Modernizing Legacy Systems Using BallerinaModernizing Legacy Systems Using Ballerina
Modernizing Legacy Systems Using Ballerina
 
The Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and InsightThe Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and Insight
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Continuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
Continuing Bonds Through AI: A Hermeneutic Reflection on ThanabotsContinuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
Continuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
 

Core data intermediate Workshop at NSSpain 2013

  • 1. Diego Freniche / @dfreniche / http://www.freniche.com Core Data Workshop
  • 3. Diego Freniche: programmer & teacher • @dfreniche • Freelance Mobile developer: iOS/Android/BB10/ webOS/... • In a former life Java Certifications Collector: SCJP 1.5, SCJP 1.6, SCWCD 1.5, SCBCD 1.3 • Some languages: BASIC, PASCAL, C, C++, Delphi, COBOL, Clipper, Visual Basic, Java, JavaScript, Objective-C Hello, World!
  • 5. Before we start... • Switch OFF phones
  • 6. Before we start... • Switch OFF phones • Been here is funny
  • 7. Before we start... • Switch OFF phones • Been here is funny • ¡Live the moment!¡Carpe diem!
  • 8. Before we start... • Switch OFF phones • Been here is funny • ¡Live the moment!¡Carpe diem! • Ask me a lot. Don’t yawn
  • 9. What you need (checklist) • a Mac with OS X capable of running Xcode 4.6.1 • last Xcode 4 installed 4.6.1 • You can also use prerelease software, if you are a registered Apple developer. No support then, sorry :-D • SimPholders installed: http://simpholders.com • SQLLite database browser: http://sqlitebrowser.sourceforge.net • (optional) set $HOME/Library folder visible, using (from a Terminal)
  • 10. Diego Freniche / http://www.freniche.com Idea: Creating the Core Data Stack
  • 11. Diego Freniche / @dfreniche / http://www.freniche.com The Core Data Stack Managed Object Context Persistent Store Coordinator Persistent Object Store Managed Object Model
  • 12. Diego Freniche / @dfreniche / http://www.freniche.com Doubts
  • 13. Diego Freniche / @dfreniche / http://www.freniche.com Doubts • Use Apple’s code?
  • 14. Diego Freniche / @dfreniche / http://www.freniche.com Doubts • Use Apple’s code? • Really?
  • 15. Diego Freniche / @dfreniche / http://www.freniche.com Doubts • Use Apple’s code? • Really? • Use a singleton?
  • 16. Diego Freniche / @dfreniche / http://www.freniche.com Doubts • Use Apple’s code? • Really? • Use a singleton? • Don’t use a singleton?
  • 17. Diego Freniche / @dfreniche / http://www.freniche.com Doubts • Use Apple’s code? • Really? • Use a singleton? • Don’t use a singleton? • Use dependency injection?
  • 18. Diego Freniche / @dfreniche / http://www.freniche.com Apple’s code
  • 19. Diego Freniche / @dfreniche / http://www.freniche.com Apple’s code - (void)saveContext { NSError *error = nil; NSManagedObjectContext *managedObjectContext = self.managedObjectContext; if (managedObjectContext != nil) { if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog(@"Unresolved error %@, %@", error, [error userInfo]); abort(); } } } #pragma mark - Core Data stack // Returns the managed object context for the application. // If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application. - (NSManagedObjectContext *)managedObjectContext { if (_managedObjectContext != nil) { return _managedObjectContext; } NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator]; if (coordinator != nil) { _managedObjectContext = [[NSManagedObjectContext alloc] init]; [_managedObjectContext setPersistentStoreCoordinator:coordinator]; } return _managedObjectContext; } // Returns the managed object model for the application. // If the model doesn't already exist, it is created from the application's model. - (NSManagedObjectModel *)managedObjectModel { if (_managedObjectModel != nil) { return _managedObjectModel; } NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"Test" withExtension:@"momd"]; _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL]; return _managedObjectModel; } // Returns the persistent store coordinator for the application. // If the coordinator doesn't already exist, it is created and the application's store added to it. - (NSPersistentStoreCoordinator *)persistentStoreCoordinator { if (_persistentStoreCoordinator != nil) { return _persistentStoreCoordinator; } NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"Test.sqlite"]; NSError *error = nil; _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]]; if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) { /* Replace this implementation with code to handle the error appropriately. abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. Typical reasons for an error here include: * The persistent store is not accessible; * The schema for the persistent store is incompatible with current managed object model. Check the error message to determine what the actual problem was. If the persistent store is not accessible, there is typically something wrong with the file path. Often, a file URL is pointing into the application's resources directory instead of a writeable directory. If you encounter schema incompatibility errors during development, you can reduce their frequency by: * Simply deleting the existing store: [[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil] * Performing automatic lightweight migration by passing the following dictionary as the options parameter: @{NSMigratePersistentStoresAutomaticallyOption:@YES, NSInferMappingModelAutomaticallyOption:@YES} Lightweight migration will only work for a limited set of schema changes; consult "Core Data Model Versioning and Data Migration Programming Guide" for details. */ NSLog(@"Unresolved error %@, %@", error, [error userInfo]); abort(); } return _persistentStoreCoordinator; } #pragma mark - Application's Documents directory // Returns the URL to the application's Documents directory. - (NSURL *)applicationDocumentsDirectory { return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject]; }
  • 20. Diego Freniche / @dfreniche / http://www.freniche.com Apple’s code problems • Core Data Stack inside AppDelegate? • Really? • Separation of concerns? • Only one Managed Object Context
  • 21. Diego Freniche / @dfreniche / http://www.freniche.com Create our own Core Data Stack
  • 22. Diego Freniche / @dfreniche / http://www.freniche.com Create our own Core Data Stack • In one “simple” method
  • 23. Diego Freniche / @dfreniche / http://www.freniche.com Create our own Core Data Stack • In one “simple” method • Singleton / not singleton?
  • 24. Diego Freniche / @dfreniche / http://www.freniche.com Create our own Core Data Stack • In one “simple” method • Singleton / not singleton? • Use both!
  • 25. Diego Freniche / @dfreniche / http://www.freniche.com Dependency injection? Or singletons FTW? • It depends :-)
  • 26. Diego Freniche / http://www.freniche.com Idea: using asserts to check threads
  • 27. Diego Freniche / http://www.freniche.com Asserts • Check if we are running UI code in the UI Thread • Check if we are NOT running Core Data code in the UI Thread
  • 28. Diego Freniche / http://www.freniche.com Asserts • Check if we are running UI code in the UI Thread • Check if we are NOT running Core Data code in the UI Thread #define DF_ASSERT_MAIN_THREAD [NSThread isMainThread]?:(NSLog(@"NOT IN MAIN THREAD"),abort())
  • 29. Diego Freniche / http://www.freniche.com Idea: create a common UITableView/Core data class
  • 30. Diego Freniche / http://www.freniche.com Idea: use an NSManagedObject subclass
  • 31. Diego Freniche / @dfreniche / http://www.freniche.com Entities Design Tips
  • 32. Diego Freniche / @dfreniche / http://www.freniche.com Entities Design Tips • Always add field order
  • 33. Diego Freniche / @dfreniche / http://www.freniche.com Entities Design Tips • Always add field order • Try to create a good UML diagram at first
  • 34. Diego Freniche / @dfreniche / http://www.freniche.com Entities Design Tips • Always add field order • Try to create a good UML diagram at first • Have an NSString constant with every Entity’s name inside .h
  • 35. Diego Freniche / @dfreniche / http://www.freniche.com Extend NSManagedObject • Editor > Create NSManagedObject subclass... • creates @dynamic properties • getter / setter generated in runtime (@property in compile time) • Core Data doesn’t know at compile time if the persistent store is going to be XML or a DB (or in-memory)
  • 36. Diego Freniche / @dfreniche / http://www.freniche.com Extend NSManagedObject • overwrite init to call designated initializer
  • 37. Diego Freniche / @dfreniche / http://www.freniche.com Extend NSManagedObject • overwrite init to call designated initializer -(id)init { NSManagedObjectContext *context = [[CoreDataStack coreDataStack] managedObjectContext]; return [self initWithEntity:[NSEntityDescription entityForName:kRETROITEM_ENTITY inManagedObjectContext:context ] insertIntoManagedObjectContext:context]; }
  • 38. Diego Freniche / @dfreniche / http://www.freniche.com Validate Properties • One for every property, if we want it • Passing parameter by reference • It should return YES if validation is passed
  • 39. Diego Freniche / @dfreniche / http://www.freniche.com Validate Properties • One for every property, if we want it • Passing parameter by reference • It should return YES if validation is passed -(BOOL)validateName:(id *)ioValue error:(NSError * __autoreleasing *)outError;
  • 40. Diego Freniche / @dfreniche / http://www.freniche.com Validator for operations • First thing: must call [super ...] • Useful to check business rules (using several properties)
  • 41. Diego Freniche / @dfreniche / http://www.freniche.com Validator for operations • First thing: must call [super ...] • Useful to check business rules (using several properties) - (BOOL)validateForDelete:(NSError **)error - (BOOL)validateForInsert:(NSError **)error - (BOOL)validateForUpdate:(NSError **)error
  • 42. Diego Freniche / @dfreniche / http://www.freniche.com Support for KVO • Good for Faults
  • 43. Diego Freniche / @dfreniche / http://www.freniche.com Support for KVO • Good for Faults - (void)willAccessValueForKey:(NSString *)key
  • 44. Diego Freniche / http://www.freniche.com Idea: use Mogenerator
  • 45. Diego Freniche / @dfreniche / http://www.freniche.com Mogenerator created by Jonathan 'Wolf' Rentzsch
  • 46. Diego Freniche / @dfreniche / http://www.freniche.com Mogenerator (quoting from the web page)
  • 47. Diego Freniche / @dfreniche / http://www.freniche.com Mogenerator (quoting from the web page) • http://rentzsch.github.io/mogenerator/
  • 48. Diego Freniche / @dfreniche / http://www.freniche.com Mogenerator (quoting from the web page) • http://rentzsch.github.io/mogenerator/ • generates Objective-C code for your Core Data custom classes
  • 49. Diego Freniche / @dfreniche / http://www.freniche.com Mogenerator (quoting from the web page) • http://rentzsch.github.io/mogenerator/ • generates Objective-C code for your Core Data custom classes • Unlike Xcode, mogenerator manages two classes per entity: one for machines, one for humans
  • 50. Diego Freniche / @dfreniche / http://www.freniche.com Mogenerator (quoting from the web page) • http://rentzsch.github.io/mogenerator/ • generates Objective-C code for your Core Data custom classes • Unlike Xcode, mogenerator manages two classes per entity: one for machines, one for humans • The machine class can always be overwritten to match the data model, with humans’ work effortlessly preserved
  • 51. Diego Freniche / @dfreniche / http://www.freniche.com Installing mogenerator
  • 52. Diego Freniche / @dfreniche / http://www.freniche.com Using it • it’s a script, so we can launch it from command line • using iTerm, DTerm, etc. • Best way: to have it inside our project • Create a new Aggregate Target (New Target > Other > Aggregate) • Add Build Phase > Add Run Script
  • 53. Diego Freniche / @dfreniche / http://www.freniche.com Using it • it’s a script, so we can launch it from command line • using iTerm, DTerm, etc. • Best way: to have it inside our project • Create a new Aggregate Target (New Target > Other > Aggregate) • Add Build Phase > Add Run Script mogenerator --template-var arc=true -m RetroStuffTracker/ RetroStuffTracker.xcdatamodeld/RetroStuffTracker.xcdatamodel/
  • 54. Diego Freniche / @dfreniche / http://www.freniche.com Two classes • _MyClass.*: machine generated • *MyClass.*: human edited • Never, ever recreate the classes again from the Core Data Model
  • 55. Diego Freniche / @dfreniche / http://www.freniche.com Two classes • _MyClass.*: machine generated • *MyClass.*: human edited • Never, ever recreate the classes again from the Core Data Model
  • 56. Diego Freniche / http://www.freniche.com Two classes
  • 57. Diego Freniche / http://www.freniche.com #import "_RetroItem.h" @interface RetroItem : _RetroItem {} // Custom logic goes here. @end Two classes
  • 58. Diego Freniche / http://www.freniche.com #import "_RetroItem.h" @interface RetroItem : _RetroItem {} // Custom logic goes here. @end #import "RetroItem.h" @interface RetroItem () // Private interface goes here. @end @implementation RetroItem // Custom logic goes here. @end Two classes
  • 59. Diego Freniche / http://www.freniche.com Idea: use Magical Record
  • 60. Diego Freniche / http://www.freniche.com Magical record != avoid Core Data at all costs
  • 61. Diego Freniche / http://www.freniche.com Magical record != avoid Core Data at all costs • Just a bunch of categories to help you write less code
  • 62. Diego Freniche / http://www.freniche.com Magical record != avoid Core Data at all costs • Just a bunch of categories to help you write less code • You have to know your sh*t
  • 63. Diego Freniche / http://www.freniche.com Magical record != avoid Core Data at all costs • Just a bunch of categories to help you write less code • You have to know your sh*t • CocoaPods friendly
  • 64. Diego Freniche / http://www.freniche.com Magical record != avoid Core Data at all costs • Just a bunch of categories to help you write less code • You have to know your sh*t • CocoaPods friendly • Ideal: use Unit testing + Mogenerator + CocoaPods + Magical Record
  • 65. Diego Freniche / http://www.freniche.com Magical record != avoid Core Data at all costs • Just a bunch of categories to help you write less code • You have to know your sh*t • CocoaPods friendly • Ideal: use Unit testing + Mogenerator + CocoaPods + Magical Record • My point: 7 people, 7 ideas, all great
  • 66. Diego Freniche / http://www.freniche.com Magical record != avoid Core Data at all costs • Just a bunch of categories to help you write less code • You have to know your sh*t • CocoaPods friendly • Ideal: use Unit testing + Mogenerator + CocoaPods + Magical Record • My point: 7 people, 7 ideas, all great • all different