Skip to main content

SyncKit for Core Data

Import SyncKit and create a synchronizer:


import SyncKit
...
synchronizer = CloudKitSynchronizer.privateSynchronizer(containerName: "your-iCloud-container-name",                                                                     managedObjectContext: self.coreDataStack.managedObjectContext)
...
// Synchronizesynchronizer.synchronize { error in    ...}

This creates a CloudKitSynchronizer object configured with a CoreDataAdapter for your model. The adapter registers changes in your model objects so they can be uploaded next time you synchronize data, and it applies changes from downloaded records to your model.

By default, the adapter will save changes to your Core Data context for you during synchronization, but custom logic can be provided by assigning a custom CoreDataAdapterDelegate.

Identifying objects#

In order for SyncKit to be able to map CloudKit records to your objects your Core Data classes should conform to PrimaryKey and implement its

static func primaryKey() -> String

method to return the name of a stored property that should be used as primary key. Primary keys should have a unique value for each object of the same class, and this value should not change in the lifetime of the object.

For example, in the example project we have:

@objc(QSCompany)public class QSCompany: NSManagedObject, PrimaryKey {    public static func primaryKey() -> String {        return "identifier"    }}
extension QSCompany {
    @nonobjc public class func fetchRequest() -> NSFetchRequest<QSCompany> {        return NSFetchRequest<QSCompany>(entityName: "QSCompany")    }
    @NSManaged public var identifier: String?    @NSManaged public var name: String?    @NSManaged public var sortIndex: NSNumber?    @NSManaged public var employees: NSSet?
}
...
func insertCompany(name: String) {  let company = NSEntityDescription.insertNewObject(forEntityName: "QSCompany", into: managedObjectContext) as! QSCompany  company.identifier = UUID().uuidString  company.name = name  try? managedObjectContext.save()}

Previous versions#

If you were using SyncKit before version 0.3.0 and you would like to adopt primary keys, check the migration guide.

Limitations#

SynCloudKit doesn't support ordered relations relationships, so those won't work. At this moment SyncKit also doesn't support many-to-many relationships.