SlideShare uma empresa Scribd logo
1 de 66
Baixar para ler 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

Mais conteĂşdo relacionado

Mais procurados

Javascript Best Practices
Javascript Best PracticesJavascript Best Practices
Javascript Best PracticesChristian Heilmann
 
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
 
Metaprogramming with javascript
Metaprogramming with javascriptMetaprogramming with javascript
Metaprogramming with javascriptAhmad Rizqi Meydiarso
 
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
 
All of Javascript
All of JavascriptAll of Javascript
All of JavascriptTogakangaroo
 
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
 

Mais procurados (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
 

Semelhante a 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
 
React nativebeginner1
React nativebeginner1React nativebeginner1
React nativebeginner1Oswald Campesato
 
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
 
tut0000021-hevery
tut0000021-heverytut0000021-hevery
tut0000021-heverytutorialsruby
 
tut0000021-hevery
tut0000021-heverytut0000021-hevery
tut0000021-heverytutorialsruby
 
Seven deadly theming sins
Seven deadly theming sinsSeven deadly theming sins
Seven deadly theming sinsGeorge Stephanis
 

Semelhante a 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
 

Mais de 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
 

Mais de 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
 

Último

Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024SynarionITSolutions
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
🐬 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
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesBoston Institute of Analytics
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 

Último (20)

Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 

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 Certications 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 eld order
  • 33. Diego Freniche / @dfreniche / http://www.freniche.com Entities Design Tips • Always add eld order • Try to create a good UML diagram at rst
  • 34. Diego Freniche / @dfreniche / http://www.freniche.com Entities Design Tips • Always add eld order • Try to create a good UML diagram at rst • 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