Core Data and CloudKit can now be linked automatically from iOS 13 and iPadOS 13, and I tried out immediately.
Environment: swift 5, Xcode 11.0
1.Check both [Use Core Data] and [Use CloudKit] when creating a project
2.After creating the project, select [TARGETS]-[Signing & Capabilities] and add [iCloud]. After that, check [CloudKit] and enter the name of [Containers].
Let's look AppDelegate
Once you have done this, take a look at the code that is automatically generated in AppDelegate.swift.
Until now, the class that accesses Core Data Stack was NSPersistentContainer, but when [use CloudKit] is checked, it changes to NSPersistentCloudKitContainer.
By using NSPersistentCloudKitContainer, linkage with CloudKit is automatically performed.
Create Entity of Core Data
Select the .xcdatamodeId file from the project and press [Add Entity] to create the Entity.
The Binary Data type is provided for saving UIImage data.
Next, execute [Editor]-[Create NSManagedObject Subclass ...] of Xcode to generate NSManagedObject class of "GoodsMaster".
The following two files are generated.
Looking at Configurations in the .xcdatamodeId file, [Used with CloudKit] is checked.
Manipulating CoreData data
The data operation is exactly the same as the previous Core Data.
Core Data operations are performed with NSManagedContext.
Get NSManagedContext through AppDelegate.
Set the data to be inserted into NSManagedObject.
If you execute NSManagerdContext's save method after setting the data, the set data will be saved.
Information required for search is set in the NSFetchRequest.
Set the search condition to NSPredicate and the sort condition to NSSortDescriptor. And pass NSPredicate and NSSortDescriptor to NSFetchRequest.
Search is executed by executing NSManagedContext fetch method with NSFetchRequest as an argument.
UPDATE is performed by first searching the data, changing the searched value, and saving.
The code looks like a combination of INSERT and SELECT.
DELETE is performed by first searching for data and deleting that data.
Let's try Core Data data linkage between devices using CloudKit.
Prepare an iPhone and iPad with iCloud settings in advance.
1.INSERT data on iPhone.
2.Select [TARGETS]-[Signing & Capabilities]-[iCloud] in Xcode and click [CloudKit Dashboard] to display the CloudKit Dashboard.
3.If you select [Schema] in CloudKit Dashboard, you can see that the Entity created in Core Data is automatically created on CloudKit.
4.If you select [Data] on the CloudKit Dashboard, you can see that the data registered on the iPhone exists on CloudKit.
5.When the program is started on the iPad and SELECT is executed, the data inserted by the iPhone is displayed.
The source code of this sample program is saved on GitHub.