A laughably simple sample app for experimenting with SwiftUI and a CloudKit-backed CoreData store.
Enabling iCloud syncing, merging, and remote-change push notifications:
lazy var persistentContainer: NSPersistentCloudKitContainer = {
let container = NSPersistentCloudKitContainer(name: "SwiftUI_Notes")
container.persistentStoreDescriptions.first?
.setOption(true as NSNumber, forKey: NSPersistentStoreRemoteChangeNotificationPostOptionKey)
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
container.viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
container.viewContext.automaticallyMergesChangesFromParent = true
return container
}()
A sample SwiftUI List
backed by a FetchedResultsController
struct NoteList: View {
@ObjectBinding var resultsController = FetchedResultsController(
with: FetchRequest(for: Note.self)
.sorted(by: \.lastModificationDate, ascending: false))
var body: some View {
NavigationView {
List {
ForEach(resultsController.objects) { note in
NoteCell(note: note)
}
}
}
}
}
FetchedResultsController
is a Swift interface around an NSFetchedResultsController
that conforms to BindableObject
.