Database Reference
In-Depth Information
import
CoreData
import
UIKit
class
AttachmentToImageAttachmentMigrationPolicyV3toV4:
NSEntityMigrationPolicy
{
}
This naming convention should look familiar to you, as it's noting that this is a
custom migration policy and is for transforming data from Attachments in model
version 3 to ImageAttachments in model version 4.
Back in the v3-to-v4 mapping model file, select the
AttachmentToImageAttachment
entity mapping. In the Entity Mapping
Inspector, fill in the
Custom Policy
field with the class name you just created,
UnCloudNotes.AttachmentToImageAttachmentMigrationPolicyV3toV4
.
Now, when Core Data runs this migration, it will create an instance of your custom
migration policy when it needs to perform a data migration for that specific set of
data. That's your chance to run any custom transformation code to do what's
needed to extract image information during migration! Now, it's time to add some
custom logic to the custom entity mapping policy.
Open
AttachmentToImageAttachmentMigrationPolicyV3toV4.swift
and add
the method to perform the migration:
override
func
createDestinationInstancesForSourceInstance(
sInstance:
NSManagedObject
!,
entityMapping mapping:
NSEntityMapping
!,
manager:
NSMigrationManager
!, error:
NSErrorPointer
) ->
Bool
{
// 1
let
newAttachment =
NSEntityDescription
.
insertNewObjectForEntityForName
(
"ImageAttachment"
,
inManagedObjectContext: manager.
destinationContext
)
as
NSManagedObject
// 2
for
propertyMapping
in
mapping.
attributeMappings
as
[
NSPropertyMapping
]! {
let
destinationName = propertyMapping.
name
if
let
valueExpression = propertyMapping.
valueExpression
{
let
context:
NSMutableDictionary
= [
"source"
: sInstance]
let
destinationValue:
AnyObject
=
valueExpression.
expressionValueWithObject
(sInstance,
context:
context
)