SlideShare a Scribd company logo
Core Data Optimization
By Gagan Vishal Mishra
Memory Vs. Performance
Core Data Optimization
2
Memory
Speed
Less More
Slow Faster
Memory Vs. Performance
Core Data Optimization
3
Memory
Speed
Less More
Slow Faster
Thread Safety In Core Data
Core Data Optimization
4
• While working with Core Data, it's important to always remember that Core Data isn't
thread safe. Core Data expects to be run on a single thread.
• NSManagedObject, NSManagedObjectContext NSPersistentStoreCoordinator aren't
thread safe.
• This doesn't mean that every Core Data operation needs to be performed on the
main thread, which is used for UI, but it means that we need to take care which
operations are executed on which threads. We have to be careful how changes from
one thread are propagated to other threads.
Thread Safety In Core Data
Core Data Optimization
5
1. NSManagedObject: NSManagedObject isn't thread safe but has an
instance objectID that returns an instance of the NSManagedObjectID class which
is thread safe. For getting
do {
let managedObject = try managedObjectContext.existingObjectWithID(objectID)
} catch let fetchError as NSError { print("(fetchError), (fetchError.userInfo)”) }
2. NSManagedObjectContext: Isn't thread safe, we can create a managed object
context for every thread that interacts with Core Data. This strategy is referred
as thread confinement. A common approach is to create thread dictionary to store
MOC.
let currentThread = NSThread.currentThread()
currentThread.threadDictionary.setObject(managedObjectContext, forKey:
"managedObjectContext")
3. NSPersistentStoreCoordinator: We can create a separate persistent store
coordinator for every thread. Which is also possible.
Multithreading & Concurrency Strategies
Core Data Optimization
6
The NSPersistentStoreCoordinator class was designed to support multiple managed
object contexts, even if those managed object contexts were created on different
threads. Because the NSManagedObjectContext class locks the persistent store
coordinator while accessing it, it is possible for multiple managed object contexts to use
the same persistent store coordinator even if those managed object contexts live on
different threads. This makes a multithreaded Core Data setup much more manageable
and less complex.
There are two ways for Core Data Concurrency
1.Notifications
2.Parent/Child Managed Object Contexts
Another option is
1.Independent Persistent Store Built with Notification & PrivateQueue
Multithreading & Concurrency Strategies
Core Data Optimization
7
There are three types of Concurrency options provided by Apple
1.MainQueueConcurrencyType: The managed object context is only accessible from
the main thread. An exception is thrown if you try to access it from any other thread.
1.PrivateQueueConcurrencyType: When creating a managed object context with a
concurrency type of PrivateQueueConcurrencyType, the managed object context is
associated with a private queue and it can only be accessed from that private queue.
2.ConfinementConcurrencyType: Apple has deprecated this concurrency type as of
iOS 9. This is the concurrency type that corresponds with the thread
confinement concept . If you create a managed object context using init(), the
concurrency type of that managed object context is ConfinementConcurrencyType.
Fetching
Core Data Optimization
8
1. Use fetchBatchSize:
• This breaks the result set into batches. The entire request will be evaluated,
and the identities of all matching objects will be recorded, but no more than
batchSize objects' data will be fetched from the persistent store at a time.
• A batch size of 0 is treated as infinite, which disables the batch faulting
behavior.
let fetchRequest = NSFetchRequest(entityName: "DataEntity")
fetchRequest.sortDescriptors = [NSSortDescriptor(key:
UFO_KEY_COREDATA_SIGHTED, ascending: false)]
fetchRequest.fetchBatchSize = 20 //Set number double to visible cells
do
{
let test = try self.managedObjectContext.executeFetchRequest(fetchRequest) as Array
print("test count is: (test.count)")
}
catch let error as NSError
{
print("Error is : (error.localizedDescription)")
}
Fetching
Core Data Optimization
9
2. Use resultType: There are four types of result type
• ManagedObjectResultType
• ManagedObjectIDResultType
• DictionaryResultType
• CountResultType
let fetchRequest = NSFetchRequest(entityName: "DataEntity")
fetchRequest.resultType = .DictionaryResultType
do
{
let arrayOfFoundRecords = try
objAppDel.tempManagedObjectContext.executeFetchRequest(fetchRequest
}
catch let error as NSError
{
print("error in fetch is : (error.localizedDescription)")
}
Fetching
Core Data Optimization
10
3. Use NSExpressionDescription & NSExpression : Instances of
NSExpressionDescription objects represent a special property description type
intended for use with the NSFetchRequest PropertiesToFetch method. An
NSExpressionDescription describes a column to be returned from a fetch that may
not appear directly as an attribute or relationship on an entity. NSExpression is used
to represent expressions in a predicate. Comparison operations in an NSPredicate
are based on two expressions, as represented by instances of the NSExpression
class. Expressions are created for constant values, key paths etc.
//Create a expression
let expressionDescription = NSExpressionDescription()
expressionDescription.name = "count"
expressionDescription.expression = NSExpression(forFunction: "count:", arguments:
[NSExpression(forKeyPath: "shape")])
//Create a fetch Request
let fetchRequest = NSFetchRequest(entityName: "DataEntity")
Fetching
Core Data Optimization
11
3. Use GroupBy: Use groupBy to aggregate for same column name.
let fetchRequest = NSFetchRequest(entityName: "DataEntity")
fetchRequest.propertiesToGroupBy = ["shape"]
4. Use propertiesToFetch: create an array of properties you want to fetch from
CoreData.
let expressionDescription = NSExpressionDescription()
expressionDescription.name = "count”
expressionDescription.expression = NSExpression(forFunction: "count:", arguments:
[NSExpression(forKeyPath: "shape")])
//Create a fetch Request
let fetchRequest = NSFetchRequest(entityName: "DataEntity")
fetchRequest.propertiesToFetch = ["shape", expressionDescription]
Fetching
Core Data Optimization
12
5. PreFetch Any Required Relationship : Prefetching allows Core Data to obtain
developer-specified related objects in a single fetch.
let entityDescription = NSEntityDescription.entityForName("Employee",
inManagedObjectContext: self.managedObjectContext)
let fetchRequest = NSFetchRequest()
fetchRequest.entity = entityDescription
fetchRequest.relationshipKeyPathsForPrefetching = ["Department"]
do{
let arrayOfFoundRecords = try
self.managedObjectContext.executeFetchRequest(fetchRequest) as Array
for ( emp in arrayOfFoundRecords )
{
print("emp is: (emp)")
print("dept is: (emp.deptEmp)")
}
}
catch let error as NSError
{
}
Fetching
Core Data Optimization
13
Fetch Summary:
1.Don’t’ fetch anything that you don’t need.
2.Always use Batch Fetch.
3.Try to use NSExpressionDescription for Fetch in other word lets allow SQLite to do
calculation.
4.Use Prefeatch (relationshipKeyPathsForPrefetching) for required relationship.
Predicates:
Core Data Optimization
14
1. Light Predicate First: Always do String Comparison in last query. For example
fetchRequest.predicate = NSPredicate(format: "shape=%@ AND duration=%d", "circle", 30)
better way it to avoid string as much as possible or use string as a second argument.
So above code will perform better if we write it as:
fetchRequest.predicate = NSPredicate(format: "duration=%d shape=%@", 30, "circle”)
2. Use BeginsWith/EndsWith: Always try to use ‘beginsWith’ in creating a predicate.
Predicates:
Core Data Optimization
15
Predicate Summary & Cost Graph
1. Do light comparison first i.e. Numerical comparison.
2. Always try to use BeginsWith/EndsWith instead of Equals/Match.
3. Don’t/avoid to use CD in comparison.
Predicate
Cost
Less More
BeginsWith/
EndsWith
Equality
==
Contains
Matches
Search
Core Data Optimization
16
1. Always used Canonical String for search process. For example
String Canonical String
TEST test
åpple apple
Green Åpple green apple
2. Always use BeginsWith/EndsWith for searching.
Printing SQL Log
Core Data Optimization
17
Product menu by selecting “Manage Schemes” and then editing the current
scheme you are using. Select the “Run “phase and then select the “Arguments”
tab. Here you will see options to set arguments and environment variables. Add
-com.apple.CoreData.SQLDebug 3 to "Arguments Passed On Launch"
18
Thank you !

More Related Content

What's hot

Zend framework 03 - singleton factory data mapper caching logging
Zend framework 03 - singleton factory data mapper caching loggingZend framework 03 - singleton factory data mapper caching logging
Zend framework 03 - singleton factory data mapper caching logging
Tricode (part of Dept)
 
Jdbc oracle
Jdbc oracleJdbc oracle
Jdbc oracle
yazidds2
 
Core data orlando i os dev group
Core data   orlando i os dev groupCore data   orlando i os dev group
Core data orlando i os dev group
Andrew Kozlik
 
Client Server Communication on iOS
Client Server Communication on iOSClient Server Communication on iOS
Client Server Communication on iOS
Make School
 
Drools
DroolsDrools
Drools
Allan Huang
 
iOSDevCamp 2011 Core Data
iOSDevCamp 2011 Core DataiOSDevCamp 2011 Core Data
iOSDevCamp 2011 Core Data
Chris Mar
 
Underscore and Backbone Models
Underscore and Backbone ModelsUnderscore and Backbone Models
Underscore and Backbone Models
Kentucky JavaScript Users Group
 
Spring frame work
Spring frame workSpring frame work
Spring frame work
husnara mohammad
 
【Unite 2017 Tokyo】ScriptableObjectを使ってプログラマーもアーティストも幸せになろう
【Unite 2017 Tokyo】ScriptableObjectを使ってプログラマーもアーティストも幸せになろう【Unite 2017 Tokyo】ScriptableObjectを使ってプログラマーもアーティストも幸せになろう
【Unite 2017 Tokyo】ScriptableObjectを使ってプログラマーもアーティストも幸せになろう
Unity Technologies Japan K.K.
 
Softshake - Offline applications
Softshake - Offline applicationsSoftshake - Offline applications
Softshake - Offline applications
jeromevdl
 
Core Data with Swift 3.0
Core Data with Swift 3.0Core Data with Swift 3.0
Core Data with Swift 3.0
Korhan Bircan
 
Advanced Core Data
Advanced Core DataAdvanced Core Data
Advanced Core Data
Make School
 
Spring data presentation
Spring data presentationSpring data presentation
Spring data presentation
Oleksii Usyk
 
Using Fuzzy Code Search to Link Code Fragments in Discussions to Source Code
Using Fuzzy Code Search to Link Code Fragments in Discussions to Source CodeUsing Fuzzy Code Search to Link Code Fragments in Discussions to Source Code
Using Fuzzy Code Search to Link Code Fragments in Discussions to Source Code
Nicolas Bettenburg
 
Ejb3 Struts Tutorial En
Ejb3 Struts Tutorial EnEjb3 Struts Tutorial En
Ejb3 Struts Tutorial En
Ankur Dongre
 
Struts2 - 101
Struts2 - 101Struts2 - 101
Struts2 - 101
Munish Gupta
 
KAAccessControl
KAAccessControlKAAccessControl
KAAccessControl
WO Community
 

What's hot (17)

Zend framework 03 - singleton factory data mapper caching logging
Zend framework 03 - singleton factory data mapper caching loggingZend framework 03 - singleton factory data mapper caching logging
Zend framework 03 - singleton factory data mapper caching logging
 
Jdbc oracle
Jdbc oracleJdbc oracle
Jdbc oracle
 
Core data orlando i os dev group
Core data   orlando i os dev groupCore data   orlando i os dev group
Core data orlando i os dev group
 
Client Server Communication on iOS
Client Server Communication on iOSClient Server Communication on iOS
Client Server Communication on iOS
 
Drools
DroolsDrools
Drools
 
iOSDevCamp 2011 Core Data
iOSDevCamp 2011 Core DataiOSDevCamp 2011 Core Data
iOSDevCamp 2011 Core Data
 
Underscore and Backbone Models
Underscore and Backbone ModelsUnderscore and Backbone Models
Underscore and Backbone Models
 
Spring frame work
Spring frame workSpring frame work
Spring frame work
 
【Unite 2017 Tokyo】ScriptableObjectを使ってプログラマーもアーティストも幸せになろう
【Unite 2017 Tokyo】ScriptableObjectを使ってプログラマーもアーティストも幸せになろう【Unite 2017 Tokyo】ScriptableObjectを使ってプログラマーもアーティストも幸せになろう
【Unite 2017 Tokyo】ScriptableObjectを使ってプログラマーもアーティストも幸せになろう
 
Softshake - Offline applications
Softshake - Offline applicationsSoftshake - Offline applications
Softshake - Offline applications
 
Core Data with Swift 3.0
Core Data with Swift 3.0Core Data with Swift 3.0
Core Data with Swift 3.0
 
Advanced Core Data
Advanced Core DataAdvanced Core Data
Advanced Core Data
 
Spring data presentation
Spring data presentationSpring data presentation
Spring data presentation
 
Using Fuzzy Code Search to Link Code Fragments in Discussions to Source Code
Using Fuzzy Code Search to Link Code Fragments in Discussions to Source CodeUsing Fuzzy Code Search to Link Code Fragments in Discussions to Source Code
Using Fuzzy Code Search to Link Code Fragments in Discussions to Source Code
 
Ejb3 Struts Tutorial En
Ejb3 Struts Tutorial EnEjb3 Struts Tutorial En
Ejb3 Struts Tutorial En
 
Struts2 - 101
Struts2 - 101Struts2 - 101
Struts2 - 101
 
KAAccessControl
KAAccessControlKAAccessControl
KAAccessControl
 

Viewers also liked

Objective-C Blocks and Grand Central Dispatch
Objective-C Blocks and Grand Central DispatchObjective-C Blocks and Grand Central Dispatch
Objective-C Blocks and Grand Central Dispatch
Matteo Battaglio
 
IBDesignable & IBInspectible
IBDesignable & IBInspectibleIBDesignable & IBInspectible
IBDesignable & IBInspectible
Gagan Vishal Mishra
 
3Com 7030-10136
3Com 7030-101363Com 7030-10136
3Com 7030-10136
savomir
 
What have you learned from your audience feedback?
What have you learned from your audience feedback?What have you learned from your audience feedback?
What have you learned from your audience feedback?
Luke Randall
 
プロジェクト
プロジェクトプロジェクト
プロジェクト
光稀 松本
 
雷諾數測試與計算
雷諾數測試與計算雷諾數測試與計算
雷諾數測試與計算
Shin-Ping Tian
 
Content Strategy Report: LPCS
Content Strategy Report: LPCSContent Strategy Report: LPCS
Content Strategy Report: LPCS
ldush
 
Cuidados de enfermería ante el accidente ofídico
Cuidados de enfermería ante el accidente ofídicoCuidados de enfermería ante el accidente ofídico
Cuidados de enfermería ante el accidente ofídico
Musete
 
Políticos [Maçonaria]
Políticos [Maçonaria]Políticos [Maçonaria]
Políticos [Maçonaria]
Do outro lado da barricada
 
Рекламный буклет налоговой системы "Свободная экономика"
Рекламный буклет налоговой системы "Свободная экономика"Рекламный буклет налоговой системы "Свободная экономика"
Рекламный буклет налоговой системы "Свободная экономика"
Michael Chernyshev
 
Perfect places
Perfect placesPerfect places
Perfect places
ismael cabezudo
 
Neibys Garcia
Neibys GarciaNeibys Garcia
Neibys Garcia
Neibys Garcia
 
Simbolos de identificacion de la concentracion de desarrollo rural saravena a...
Simbolos de identificacion de la concentracion de desarrollo rural saravena a...Simbolos de identificacion de la concentracion de desarrollo rural saravena a...
Simbolos de identificacion de la concentracion de desarrollo rural saravena a...
Yeritza Neley Jimes Mejia
 
Presentacionrelacionespublicas 101125162209-phpapp02
Presentacionrelacionespublicas 101125162209-phpapp02Presentacionrelacionespublicas 101125162209-phpapp02
Presentacionrelacionespublicas 101125162209-phpapp02
Fabricio Jonathan Cruz Chicaiza
 
Mejorar la usabilidad y la conversion con WPO en Wordpress
Mejorar la usabilidad y la conversion con WPO en WordpressMejorar la usabilidad y la conversion con WPO en Wordpress
Mejorar la usabilidad y la conversion con WPO en Wordpress
Raiola Networks
 
Creative critical reflection (short film) by Muhammad Hammaz
Creative critical reflection (short film) by Muhammad HammazCreative critical reflection (short film) by Muhammad Hammaz
Creative critical reflection (short film) by Muhammad Hammaz
Hammaz Buksh
 
CONÓCETE Y TE SORPRENDERÁS!
CONÓCETE Y TE SORPRENDERÁS!CONÓCETE Y TE SORPRENDERÁS!
CONÓCETE Y TE SORPRENDERÁS!
Ricardo González Caballero
 

Viewers also liked (18)

Objective-C Blocks and Grand Central Dispatch
Objective-C Blocks and Grand Central DispatchObjective-C Blocks and Grand Central Dispatch
Objective-C Blocks and Grand Central Dispatch
 
IBDesignable & IBInspectible
IBDesignable & IBInspectibleIBDesignable & IBInspectible
IBDesignable & IBInspectible
 
3Com 7030-10136
3Com 7030-101363Com 7030-10136
3Com 7030-10136
 
What have you learned from your audience feedback?
What have you learned from your audience feedback?What have you learned from your audience feedback?
What have you learned from your audience feedback?
 
プロジェクト
プロジェクトプロジェクト
プロジェクト
 
雷諾數測試與計算
雷諾數測試與計算雷諾數測試與計算
雷諾數測試與計算
 
Content Strategy Report: LPCS
Content Strategy Report: LPCSContent Strategy Report: LPCS
Content Strategy Report: LPCS
 
Cuidados de enfermería ante el accidente ofídico
Cuidados de enfermería ante el accidente ofídicoCuidados de enfermería ante el accidente ofídico
Cuidados de enfermería ante el accidente ofídico
 
Políticos [Maçonaria]
Políticos [Maçonaria]Políticos [Maçonaria]
Políticos [Maçonaria]
 
Рекламный буклет налоговой системы "Свободная экономика"
Рекламный буклет налоговой системы "Свободная экономика"Рекламный буклет налоговой системы "Свободная экономика"
Рекламный буклет налоговой системы "Свободная экономика"
 
Perfect places
Perfect placesPerfect places
Perfect places
 
Neibys Garcia
Neibys GarciaNeibys Garcia
Neibys Garcia
 
Poster1
Poster1Poster1
Poster1
 
Simbolos de identificacion de la concentracion de desarrollo rural saravena a...
Simbolos de identificacion de la concentracion de desarrollo rural saravena a...Simbolos de identificacion de la concentracion de desarrollo rural saravena a...
Simbolos de identificacion de la concentracion de desarrollo rural saravena a...
 
Presentacionrelacionespublicas 101125162209-phpapp02
Presentacionrelacionespublicas 101125162209-phpapp02Presentacionrelacionespublicas 101125162209-phpapp02
Presentacionrelacionespublicas 101125162209-phpapp02
 
Mejorar la usabilidad y la conversion con WPO en Wordpress
Mejorar la usabilidad y la conversion con WPO en WordpressMejorar la usabilidad y la conversion con WPO en Wordpress
Mejorar la usabilidad y la conversion con WPO en Wordpress
 
Creative critical reflection (short film) by Muhammad Hammaz
Creative critical reflection (short film) by Muhammad HammazCreative critical reflection (short film) by Muhammad Hammaz
Creative critical reflection (short film) by Muhammad Hammaz
 
CONÓCETE Y TE SORPRENDERÁS!
CONÓCETE Y TE SORPRENDERÁS!CONÓCETE Y TE SORPRENDERÁS!
CONÓCETE Y TE SORPRENDERÁS!
 

Similar to Core Data Performance Guide Line

Connecting to a REST API in iOS
Connecting to a REST API in iOSConnecting to a REST API in iOS
Connecting to a REST API in iOS
gillygize
 
Intro to Core Data
Intro to Core DataIntro to Core Data
Intro to Core Data
Make School
 
CocoaHeads PDX 2014 01 23 : CoreData and iCloud Improvements iOS7 / OSX Maver...
CocoaHeads PDX 2014 01 23 : CoreData and iCloud Improvements iOS7 / OSX Maver...CocoaHeads PDX 2014 01 23 : CoreData and iCloud Improvements iOS7 / OSX Maver...
CocoaHeads PDX 2014 01 23 : CoreData and iCloud Improvements iOS7 / OSX Maver...
smn-automate
 
Simpler Core Data with RubyMotion
Simpler Core Data with RubyMotionSimpler Core Data with RubyMotion
Simpler Core Data with RubyMotion
Stefan Haflidason
 
Share point 2013 coding standards and best practices 1.0
Share point 2013 coding standards and best practices 1.0Share point 2013 coding standards and best practices 1.0
Share point 2013 coding standards and best practices 1.0
LiquidHub
 
EMF Tips n Tricks
EMF Tips n TricksEMF Tips n Tricks
EMF Tips n Tricks
Kaniska Mandal
 
EJB Clients
EJB ClientsEJB Clients
EJB Clients
Roy Antony Arnold G
 
.NET Core, ASP.NET Core Course, Session 14
.NET Core, ASP.NET Core Course, Session 14.NET Core, ASP.NET Core Course, Session 14
.NET Core, ASP.NET Core Course, Session 14
aminmesbahi
 
Core Data
Core DataCore Data
Core Data
Robert Brown
 
Session 5 Tp5
Session 5 Tp5Session 5 Tp5
Session 5 Tp5
phanleson
 
Ruby on Rails Developer - Allerin
Ruby on Rails Developer - AllerinRuby on Rails Developer - Allerin
Ruby on Rails Developer - Allerin
Lauree R
 
[2 d1] elasticsearch 성능 최적화
[2 d1] elasticsearch 성능 최적화[2 d1] elasticsearch 성능 최적화
[2 d1] elasticsearch 성능 최적화
Henry Jeong
 
[2D1]Elasticsearch 성능 최적화
[2D1]Elasticsearch 성능 최적화[2D1]Elasticsearch 성능 최적화
[2D1]Elasticsearch 성능 최적화
NAVER D2
 
Concurrency and Thread-Safe Data Processing in Background Tasks
Concurrency and Thread-Safe Data Processing in Background TasksConcurrency and Thread-Safe Data Processing in Background Tasks
Concurrency and Thread-Safe Data Processing in Background Tasks
WO Community
 
ASP.NET Session 11 12
ASP.NET Session 11 12ASP.NET Session 11 12
ASP.NET Session 11 12
Sisir Ghosh
 
4.4 Java Database Connectivity with 5 Steps.pptx
4.4 Java Database Connectivity with 5 Steps.pptx4.4 Java Database Connectivity with 5 Steps.pptx
4.4 Java Database Connectivity with 5 Steps.pptx
Punithavel Ramani
 
Scripting as a Second Language
Scripting as a Second LanguageScripting as a Second Language
Scripting as a Second Language
Rob Dunn
 
Data Binding in Silverlight
Data Binding in SilverlightData Binding in Silverlight
Data Binding in Silverlight
Boulos Dib
 
Local data storage for mobile apps
Local data storage for mobile appsLocal data storage for mobile apps
Local data storage for mobile apps
Ivano Malavolta
 
REST/JSON/CoreData Example Code - A Tour
REST/JSON/CoreData Example Code - A TourREST/JSON/CoreData Example Code - A Tour
REST/JSON/CoreData Example Code - A Tour
Carl Brown
 

Similar to Core Data Performance Guide Line (20)

Connecting to a REST API in iOS
Connecting to a REST API in iOSConnecting to a REST API in iOS
Connecting to a REST API in iOS
 
Intro to Core Data
Intro to Core DataIntro to Core Data
Intro to Core Data
 
CocoaHeads PDX 2014 01 23 : CoreData and iCloud Improvements iOS7 / OSX Maver...
CocoaHeads PDX 2014 01 23 : CoreData and iCloud Improvements iOS7 / OSX Maver...CocoaHeads PDX 2014 01 23 : CoreData and iCloud Improvements iOS7 / OSX Maver...
CocoaHeads PDX 2014 01 23 : CoreData and iCloud Improvements iOS7 / OSX Maver...
 
Simpler Core Data with RubyMotion
Simpler Core Data with RubyMotionSimpler Core Data with RubyMotion
Simpler Core Data with RubyMotion
 
Share point 2013 coding standards and best practices 1.0
Share point 2013 coding standards and best practices 1.0Share point 2013 coding standards and best practices 1.0
Share point 2013 coding standards and best practices 1.0
 
EMF Tips n Tricks
EMF Tips n TricksEMF Tips n Tricks
EMF Tips n Tricks
 
EJB Clients
EJB ClientsEJB Clients
EJB Clients
 
.NET Core, ASP.NET Core Course, Session 14
.NET Core, ASP.NET Core Course, Session 14.NET Core, ASP.NET Core Course, Session 14
.NET Core, ASP.NET Core Course, Session 14
 
Core Data
Core DataCore Data
Core Data
 
Session 5 Tp5
Session 5 Tp5Session 5 Tp5
Session 5 Tp5
 
Ruby on Rails Developer - Allerin
Ruby on Rails Developer - AllerinRuby on Rails Developer - Allerin
Ruby on Rails Developer - Allerin
 
[2 d1] elasticsearch 성능 최적화
[2 d1] elasticsearch 성능 최적화[2 d1] elasticsearch 성능 최적화
[2 d1] elasticsearch 성능 최적화
 
[2D1]Elasticsearch 성능 최적화
[2D1]Elasticsearch 성능 최적화[2D1]Elasticsearch 성능 최적화
[2D1]Elasticsearch 성능 최적화
 
Concurrency and Thread-Safe Data Processing in Background Tasks
Concurrency and Thread-Safe Data Processing in Background TasksConcurrency and Thread-Safe Data Processing in Background Tasks
Concurrency and Thread-Safe Data Processing in Background Tasks
 
ASP.NET Session 11 12
ASP.NET Session 11 12ASP.NET Session 11 12
ASP.NET Session 11 12
 
4.4 Java Database Connectivity with 5 Steps.pptx
4.4 Java Database Connectivity with 5 Steps.pptx4.4 Java Database Connectivity with 5 Steps.pptx
4.4 Java Database Connectivity with 5 Steps.pptx
 
Scripting as a Second Language
Scripting as a Second LanguageScripting as a Second Language
Scripting as a Second Language
 
Data Binding in Silverlight
Data Binding in SilverlightData Binding in Silverlight
Data Binding in Silverlight
 
Local data storage for mobile apps
Local data storage for mobile appsLocal data storage for mobile apps
Local data storage for mobile apps
 
REST/JSON/CoreData Example Code - A Tour
REST/JSON/CoreData Example Code - A TourREST/JSON/CoreData Example Code - A Tour
REST/JSON/CoreData Example Code - A Tour
 

More from Gagan Vishal Mishra

iOS Versions history
iOS Versions historyiOS Versions history
iOS Versions history
Gagan Vishal Mishra
 
Core data optimization
Core data optimizationCore data optimization
Core data optimization
Gagan Vishal Mishra
 
Jenkins CI/CD setup for iOS in Mac OSX
Jenkins CI/CD setup for iOS in Mac OSXJenkins CI/CD setup for iOS in Mac OSX
Jenkins CI/CD setup for iOS in Mac OSX
Gagan Vishal Mishra
 
Linking between JIRA & GIT, Smart Commit Command
Linking between JIRA & GIT, Smart Commit Command Linking between JIRA & GIT, Smart Commit Command
Linking between JIRA & GIT, Smart Commit Command
Gagan Vishal Mishra
 
Backbase CXP Manager Setup
Backbase CXP Manager SetupBackbase CXP Manager Setup
Backbase CXP Manager Setup
Gagan Vishal Mishra
 
Dynamic databinding
Dynamic databindingDynamic databinding
Dynamic databinding
Gagan Vishal Mishra
 
Visual Formatting Language in iOS
Visual Formatting Language in iOSVisual Formatting Language in iOS
Visual Formatting Language in iOS
Gagan Vishal Mishra
 
Search API
Search APISearch API

More from Gagan Vishal Mishra (8)

iOS Versions history
iOS Versions historyiOS Versions history
iOS Versions history
 
Core data optimization
Core data optimizationCore data optimization
Core data optimization
 
Jenkins CI/CD setup for iOS in Mac OSX
Jenkins CI/CD setup for iOS in Mac OSXJenkins CI/CD setup for iOS in Mac OSX
Jenkins CI/CD setup for iOS in Mac OSX
 
Linking between JIRA & GIT, Smart Commit Command
Linking between JIRA & GIT, Smart Commit Command Linking between JIRA & GIT, Smart Commit Command
Linking between JIRA & GIT, Smart Commit Command
 
Backbase CXP Manager Setup
Backbase CXP Manager SetupBackbase CXP Manager Setup
Backbase CXP Manager Setup
 
Dynamic databinding
Dynamic databindingDynamic databinding
Dynamic databinding
 
Visual Formatting Language in iOS
Visual Formatting Language in iOSVisual Formatting Language in iOS
Visual Formatting Language in iOS
 
Search API
Search APISearch API
Search API
 

Recently uploaded

Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Malak Abu Hammad
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
Quotidiano Piemontese
 
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
Neo4j
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
Kari Kakkonen
 
Full-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalizationFull-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalization
Zilliz
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
Alpen-Adria-Universität
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
SOFTTECHHUB
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
Matthew Sinclair
 
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
Neo4j
 
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
Edge AI and Vision Alliance
 
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
Neo4j
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
Zilliz
 
How to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For FlutterHow to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For Flutter
Daiki Mogmet Ito
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
名前 です男
 
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success StoryDriving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Safe Software
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
innovationoecd
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
DianaGray10
 
Infrastructure Challenges in Scaling RAG with Custom AI models
Infrastructure Challenges in Scaling RAG with Custom AI modelsInfrastructure Challenges in Scaling RAG with Custom AI models
Infrastructure Challenges in Scaling RAG with Custom AI models
Zilliz
 
GenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizationsGenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizations
kumardaparthi1024
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
Adtran
 

Recently uploaded (20)

Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
 
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
 
Full-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalizationFull-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalization
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
 
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
 
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
 
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
 
How to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For FlutterHow to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For Flutter
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
 
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success StoryDriving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success Story
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
 
Infrastructure Challenges in Scaling RAG with Custom AI models
Infrastructure Challenges in Scaling RAG with Custom AI modelsInfrastructure Challenges in Scaling RAG with Custom AI models
Infrastructure Challenges in Scaling RAG with Custom AI models
 
GenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizationsGenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizations
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
 

Core Data Performance Guide Line

  • 1. Core Data Optimization By Gagan Vishal Mishra
  • 2. Memory Vs. Performance Core Data Optimization 2 Memory Speed Less More Slow Faster
  • 3. Memory Vs. Performance Core Data Optimization 3 Memory Speed Less More Slow Faster
  • 4. Thread Safety In Core Data Core Data Optimization 4 • While working with Core Data, it's important to always remember that Core Data isn't thread safe. Core Data expects to be run on a single thread. • NSManagedObject, NSManagedObjectContext NSPersistentStoreCoordinator aren't thread safe. • This doesn't mean that every Core Data operation needs to be performed on the main thread, which is used for UI, but it means that we need to take care which operations are executed on which threads. We have to be careful how changes from one thread are propagated to other threads.
  • 5. Thread Safety In Core Data Core Data Optimization 5 1. NSManagedObject: NSManagedObject isn't thread safe but has an instance objectID that returns an instance of the NSManagedObjectID class which is thread safe. For getting do { let managedObject = try managedObjectContext.existingObjectWithID(objectID) } catch let fetchError as NSError { print("(fetchError), (fetchError.userInfo)”) } 2. NSManagedObjectContext: Isn't thread safe, we can create a managed object context for every thread that interacts with Core Data. This strategy is referred as thread confinement. A common approach is to create thread dictionary to store MOC. let currentThread = NSThread.currentThread() currentThread.threadDictionary.setObject(managedObjectContext, forKey: "managedObjectContext") 3. NSPersistentStoreCoordinator: We can create a separate persistent store coordinator for every thread. Which is also possible.
  • 6. Multithreading & Concurrency Strategies Core Data Optimization 6 The NSPersistentStoreCoordinator class was designed to support multiple managed object contexts, even if those managed object contexts were created on different threads. Because the NSManagedObjectContext class locks the persistent store coordinator while accessing it, it is possible for multiple managed object contexts to use the same persistent store coordinator even if those managed object contexts live on different threads. This makes a multithreaded Core Data setup much more manageable and less complex. There are two ways for Core Data Concurrency 1.Notifications 2.Parent/Child Managed Object Contexts Another option is 1.Independent Persistent Store Built with Notification & PrivateQueue
  • 7. Multithreading & Concurrency Strategies Core Data Optimization 7 There are three types of Concurrency options provided by Apple 1.MainQueueConcurrencyType: The managed object context is only accessible from the main thread. An exception is thrown if you try to access it from any other thread. 1.PrivateQueueConcurrencyType: When creating a managed object context with a concurrency type of PrivateQueueConcurrencyType, the managed object context is associated with a private queue and it can only be accessed from that private queue. 2.ConfinementConcurrencyType: Apple has deprecated this concurrency type as of iOS 9. This is the concurrency type that corresponds with the thread confinement concept . If you create a managed object context using init(), the concurrency type of that managed object context is ConfinementConcurrencyType.
  • 8. Fetching Core Data Optimization 8 1. Use fetchBatchSize: • This breaks the result set into batches. The entire request will be evaluated, and the identities of all matching objects will be recorded, but no more than batchSize objects' data will be fetched from the persistent store at a time. • A batch size of 0 is treated as infinite, which disables the batch faulting behavior. let fetchRequest = NSFetchRequest(entityName: "DataEntity") fetchRequest.sortDescriptors = [NSSortDescriptor(key: UFO_KEY_COREDATA_SIGHTED, ascending: false)] fetchRequest.fetchBatchSize = 20 //Set number double to visible cells do { let test = try self.managedObjectContext.executeFetchRequest(fetchRequest) as Array print("test count is: (test.count)") } catch let error as NSError { print("Error is : (error.localizedDescription)") }
  • 9. Fetching Core Data Optimization 9 2. Use resultType: There are four types of result type • ManagedObjectResultType • ManagedObjectIDResultType • DictionaryResultType • CountResultType let fetchRequest = NSFetchRequest(entityName: "DataEntity") fetchRequest.resultType = .DictionaryResultType do { let arrayOfFoundRecords = try objAppDel.tempManagedObjectContext.executeFetchRequest(fetchRequest } catch let error as NSError { print("error in fetch is : (error.localizedDescription)") }
  • 10. Fetching Core Data Optimization 10 3. Use NSExpressionDescription & NSExpression : Instances of NSExpressionDescription objects represent a special property description type intended for use with the NSFetchRequest PropertiesToFetch method. An NSExpressionDescription describes a column to be returned from a fetch that may not appear directly as an attribute or relationship on an entity. NSExpression is used to represent expressions in a predicate. Comparison operations in an NSPredicate are based on two expressions, as represented by instances of the NSExpression class. Expressions are created for constant values, key paths etc. //Create a expression let expressionDescription = NSExpressionDescription() expressionDescription.name = "count" expressionDescription.expression = NSExpression(forFunction: "count:", arguments: [NSExpression(forKeyPath: "shape")]) //Create a fetch Request let fetchRequest = NSFetchRequest(entityName: "DataEntity")
  • 11. Fetching Core Data Optimization 11 3. Use GroupBy: Use groupBy to aggregate for same column name. let fetchRequest = NSFetchRequest(entityName: "DataEntity") fetchRequest.propertiesToGroupBy = ["shape"] 4. Use propertiesToFetch: create an array of properties you want to fetch from CoreData. let expressionDescription = NSExpressionDescription() expressionDescription.name = "count” expressionDescription.expression = NSExpression(forFunction: "count:", arguments: [NSExpression(forKeyPath: "shape")]) //Create a fetch Request let fetchRequest = NSFetchRequest(entityName: "DataEntity") fetchRequest.propertiesToFetch = ["shape", expressionDescription]
  • 12. Fetching Core Data Optimization 12 5. PreFetch Any Required Relationship : Prefetching allows Core Data to obtain developer-specified related objects in a single fetch. let entityDescription = NSEntityDescription.entityForName("Employee", inManagedObjectContext: self.managedObjectContext) let fetchRequest = NSFetchRequest() fetchRequest.entity = entityDescription fetchRequest.relationshipKeyPathsForPrefetching = ["Department"] do{ let arrayOfFoundRecords = try self.managedObjectContext.executeFetchRequest(fetchRequest) as Array for ( emp in arrayOfFoundRecords ) { print("emp is: (emp)") print("dept is: (emp.deptEmp)") } } catch let error as NSError { }
  • 13. Fetching Core Data Optimization 13 Fetch Summary: 1.Don’t’ fetch anything that you don’t need. 2.Always use Batch Fetch. 3.Try to use NSExpressionDescription for Fetch in other word lets allow SQLite to do calculation. 4.Use Prefeatch (relationshipKeyPathsForPrefetching) for required relationship.
  • 14. Predicates: Core Data Optimization 14 1. Light Predicate First: Always do String Comparison in last query. For example fetchRequest.predicate = NSPredicate(format: "shape=%@ AND duration=%d", "circle", 30) better way it to avoid string as much as possible or use string as a second argument. So above code will perform better if we write it as: fetchRequest.predicate = NSPredicate(format: "duration=%d shape=%@", 30, "circle”) 2. Use BeginsWith/EndsWith: Always try to use ‘beginsWith’ in creating a predicate.
  • 15. Predicates: Core Data Optimization 15 Predicate Summary & Cost Graph 1. Do light comparison first i.e. Numerical comparison. 2. Always try to use BeginsWith/EndsWith instead of Equals/Match. 3. Don’t/avoid to use CD in comparison. Predicate Cost Less More BeginsWith/ EndsWith Equality == Contains Matches
  • 16. Search Core Data Optimization 16 1. Always used Canonical String for search process. For example String Canonical String TEST test åpple apple Green Åpple green apple 2. Always use BeginsWith/EndsWith for searching.
  • 17. Printing SQL Log Core Data Optimization 17 Product menu by selecting “Manage Schemes” and then editing the current scheme you are using. Select the “Run “phase and then select the “Arguments” tab. Here you will see options to set arguments and environment variables. Add -com.apple.CoreData.SQLDebug 3 to "Arguments Passed On Launch"

Editor's Notes

  1. http://www.cimgf.com/2015/06/25/core-data-and-aggregate-fetches-in-swift/ https://www.bignerdranch.com/blog/new-in-core-data-and-ios-8-batch-updating/
  2. http://www.cimgf.com/2015/06/25/core-data-and-aggregate-fetches-in-swift/ https://www.bignerdranch.com/blog/new-in-core-data-and-ios-8-batch-updating/
  3. http://www.cimgf.com/2015/06/25/core-data-and-aggregate-fetches-in-swift/ https://www.bignerdranch.com/blog/new-in-core-data-and-ios-8-batch-updating/
  4. http://www.cimgf.com/2015/06/25/core-data-and-aggregate-fetches-in-swift/ https://www.bignerdranch.com/blog/new-in-core-data-and-ios-8-batch-updating/
  5. http://www.cimgf.com/2015/06/25/core-data-and-aggregate-fetches-in-swift/ https://www.bignerdranch.com/blog/new-in-core-data-and-ios-8-batch-updating/
  6. http://www.cimgf.com/2015/06/25/core-data-and-aggregate-fetches-in-swift/ https://www.bignerdranch.com/blog/new-in-core-data-and-ios-8-batch-updating/
  7. http://www.cimgf.com/2015/06/25/core-data-and-aggregate-fetches-in-swift/ https://www.bignerdranch.com/blog/new-in-core-data-and-ios-8-batch-updating/
  8. http://www.cimgf.com/2015/06/25/core-data-and-aggregate-fetches-in-swift/ https://www.bignerdranch.com/blog/new-in-core-data-and-ios-8-batch-updating/
  9. http://www.cimgf.com/2015/06/25/core-data-and-aggregate-fetches-in-swift/ https://www.bignerdranch.com/blog/new-in-core-data-and-ios-8-batch-updating/