Successfully reported this slideshow.
Your SlideShare is downloading. ×

Things you might have missed from CoreData

Ad
Ad
Ad
Ad
Ad
Ad
Ad
Ad
Ad
Ad
Ad
Loading in …3
×

Check these out next

1 of 30 Ad

More Related Content

Similar to Things you might have missed from CoreData (20)

Advertisement

Recently uploaded (20)

Things you might have missed from CoreData

  1. 1. Advanced CoreData CocoaHeads Moscow
  2. 2. Сергей Пронин Full-stack developer CTO, Senior Dev, Co-Founder
 App in the Air Senior Developer
 Empatika Преподаватель
 НИУ-ВШЭ
 Департамент Программной Инженерии
  3. 3. App in the Air
  4. 4. http://appintheair.mobi/
  5. 5. Advanced CoreData • CoreData stack set-ups • High-performance Concurrency • Migration • Runtime models
  6. 6. CoreData stack set-ups
  7. 7. Default • Предлагается Xcode при создании проекта • Самый простой в понимании • Вся работа проходит через Main (UI) thread • Подходит для маленьких проектов с примитивным хранением Store Coordinator Context Main
  8. 8. Nested Simple • I/O операции делаются асинхронно через PrivateConcurrency context • Mid-level проекты, где данные нужны в момент доступа • Стандартный MagicalRecord работает таким образом • Main thread страдает при больших объемах данных Context Private Store Coordinator Context Main
  9. 9. Nested Workers • I/O операции делаются асинхронно через PrivateConcurrency context • Одна из самых популярных сборок вложенных контекстов асинхронности • Ведет себя лучше, чем Nested Simple на больших объемах • Изменения из workers все равно проходят через Main workers Context Private Store Coordinator Context Main Context Private Context Private
  10. 10. High-Performance Concurrent Classic • I/O операции делаются асинхронно через PrivateConcurrency context • Ведет себя почти идеально на больших объемах • Изменения из worker не касаются Main • Нужно “затягивать” изменения • Записи из Main синхронны — нужно сохранять большие объемы отдельно worker Store Coordinator Context Private Context Main
  11. 11. High-Performance Concurrent Modified • I/O операции делаются асинхронно через PrivateConcurrency context • Ведет себя почти идеально на больших объемах • Изменения из worker не касаются Main • Нужно “затягивать” изменения через 
 NSManagedObjectContextDidSaveNotification • Записи Main асинхронны — удобство использования worker Context Private Store Coordinator Context Private Context Main
  12. 12. Performance All Off-main Main Default 4.2s 0.0s 4.2s Nested
 simple 18.647s 15.637s 3.010s Nested
 workers 18.927s 15.85s 3.077s HP Classic 21.05s 20.9s 0.158s
  13. 13. Материалы 1. The concurrent Core Data Stack 2. Backstage with Nested Managed Object Contexts 3. Concurrent Core Data Stacks – Performance Shootout 4. Не нужно бояться CoreData
  14. 14. Migration
  15. 15. Light-weight migration NSMigratePersistentStoresAutomaticallyOption: true
 NSInferMappingModelAutomaticallyOption: true • Удаление entity, отношения или атрибута • Переименование с renamingIdentifier • Добавление атрибута • Изменение иерархии
  16. 16. Heavy-weight migration • Все, что не подходит под light-weight миграцию • Изменение типа атрибута
 NSMigrationManager — отвечает за миграцию, принимает две модели (“из” и “в”) NSMappingModel — хранит набор NSEntityMapping NSEntityMapping — соотношение двух NSEntityDescription между которыми будет маппинг NSEntityMigrationPolicy — “политика” миграции, обрабатывает преобразование каждого объекта
  17. 17. NSEntityMapping let eMapping = NSEntityMapping() eMapping.mappingType = .TransformEntityMappingType eMapping.entityMigrationPolicyClassName = “MyEntityMigrationPolicy" eMapping.sourceEntityName = fromEntity.name eMapping.sourceEntityVersionHash = fromEntity eMapping.sourceExpression = NSExpression(format: MANTRA) eMapping.destinationEntityVersionHash = toEntity.versionHash eMapping.destinationEntityName = toEntity.name let idMapping = NSPropertyMapping() idMapping.name = "_id" idMapping.valueExpression = NSExpression(format: 
 “FUNCTION($source, "valueForKey:", ”_id")") eMapping.attributeMappings = [idMapping] mappings.append(entityMapping) MANTRA ”FETCH(
 FUNCTION($manager, "fetchRequestForSourceEntityNamed:predicateString:",
 "(fromEntity.name)", "TRUEPREDICATE"),
 FUNCTION($manager, "sourceContext"), 
 NO)"
  18. 18. NSMappingModel let mappingModel = NSMappingModel() //... mappingModel.entityMapping = mappings
  19. 19. NSMigrationManager let migrationManager = NSMigrationManager(
 sourceModel: sourceModel,
 destinationModel: destinationModel) //... migrationManager.migrateStoreFromURL(store1URL,
 type: NSSQLiteStoreType, options: nil,
 withMappingModel: mappingModel,
 toDestinationURL: store2URL,
 destinationType: NSSQLiteStoreType,
 destinationOptions: nil, 
 error: &error)
  20. 20. NSEntityMigrationPolicy
 subclass func createDestinationInstancesForSourceInstance(
 _ sInstance: NSManagedObject, entityMapping mapping: NSEntityMapping,
 manager: NSMigrationManager, error: NSErrorPointer) -> Bool { let dInstance = NSEntityDescription
 .insertNewObjectForEntityForName(mapping.destinationEntityName,
 inManagedObjectContext: manager.destinationContext) for (key, value) in dInstance.entity.propertiesByName { let oldValue = sInstance.valueForKey(key as! String) let convertedValue = convert(oldValue) dInstance.setValue(convertedValue, forKey: key as! String) } manager.associateSourceInstance(sInstance,
 withDestinationInstance: dInstance, forEntityMapping: mapping) return true }
  21. 21. Launch Arguments -com.apple.CoreData.MigrationDebug 1
 Описывает процесс миграции + ошибки -com.apple.CoreData.SQLDebug 1 (3)
 Логгирует настоящие SQL запросы на каждый store
  22. 22. Материалы 1. Custom CoreData migration 2. Apple Guide: Core Data migration
  23. 23. Runtime Models
  24. 24. Runtime models Advanced caching — write once, use anytime — грамотно написанное runtime построение модели позволяет полностью настраивать store с бекэнда
  25. 25. let entity = NSEntityDescription() entity.name = “Person” //если есть entity.managedObjectClassName = “Person” var properties = [NSAttributeDescription]() let attribute = NSAttributeDescription() attribute.name = “_id” attribute.optional = false attribute.indexed = true attribute.type = .StringAttributeType properties.append(attribute) //... entity.properties = properties let model = NSManagedObjectModel() model.entities = [entity] let coordinator = NSPersistentStoreCoordinator( managedObjectModel: model)
  26. 26. Материалы 1. Simple Core Data model in Runtime 2. Generating Registered Runtime Classes 3. Mike Ash Blog: Runtime Ambassador
  27. 27. Key Points • Экспериментировать со сборками CoreData стеков, чтобы найти удачный вариант • Сложная миграция — это просто • Вся CoreData без труда строится в runtime, позволяя делать “гибкие” модели с бекенда
  28. 28. Курс НИУ ВШЭ — Swift Идёт прямо сейчас. Все материалы на русском языке. https://itunes.apple.com/ru/course/razrabotka-ios-prilozenij/id941293188?l=en iTunes U
  29. 29. Спасибо!
 @spronin sergey@pronin.me

×