Dynamic search in one to many core data relationship in SwiftUI - core-data

I have 2 entities in my CoreData model.Book and Quotes. Book has one to many relationship with Quotes. I'm displaying all the quotes with related book in a sectioned list. Section headers show the book titles and related quotes are shown in QuoteView(). I want to add a dynamic search to find a specific quote. But I could only display all the quotes related to a book. This is because I'm filtering the book that contains the quote, not the quote itself. What I want to achieve is to display only the specific quote. I could fetch all the quotes and filter them, but in this case I cannot show the related books. I could not figure out how to filter a specific attribute in a one to many relationship with predicates. Hope I could explain.
Here is my code:
#FetchRequest(sortDescriptors: [NSSortDescriptor(keyPath: \Book.title, ascending: true)])
private var books: FetchedResults<Book>
#State private var searchText: String = ""
var searchQuery: Binding<String> {
Binding {
searchText
} set: { newValue in
searchText = newValue
guard !newValue.isEmpty else {
books.nsPredicate = nil
return
}
books.nsPredicate = NSPredicate( format: "quotes.quote contains[cd] %#", newValue)
}
}
var body: some View {
NavigationView{
List{
ForEach(books, id: \.self){ book in
if book.quotes?.count != 0 {
Section(header:Text(book.title ?? "")
.foregroundColor(Color("OrangeColor"))
.font(.custom("Montserrat-Bold", size: 18))){
ForEach(Array((book.quotes as? Set<Quote> ?? []).sorted(by: { $0.quote! < $1.quote! })), id:\.self){ quote in
NavigationLink{
DetailQuoteView(quote: quote, selectedBook: book)
} label: {
QuoteView(quote: quote) }
}
.onDelete{
self.delete(at: $0, in: book)}
}
}
}
}
.searchable(text: searchQuery)
//code...
}
}
Thanks for your help.

Related

SwiftUI UISearchController replacement: search field, results and some scrollable content fail to coexist in a meaningful manner

Starting with this
var body: some View {
ScrollView {
VStack(spacing: 0.0) {
Some views here
}
}
.edgesIgnoringSafeArea(.top)
}
How would I add
List(suggestions, rowContent: { text in
NavigationLink(destination: ResultsPullerView(searchText: text)) {
Text(text)
}
})
.searchable(text: $searchText)
on top if that scrollable content?
Cause no matter how I hoax this together when
#State private var suggestions: [String] = []
gets populated (non empty) the search results are not squeezed in (or, better yet, shown on top of
"Some views here"
So what I want to achieve in different terms: search field is on top, scrollable content driven by the search results is underneath, drop down with search suggestions either temporarily squeeses scrollable content down or is overlaid on top like a modal sheet.
Thanks!
If you are looking for UIKit like search behaviour you have to display your results in an overlay:
1. Let's declare a screen to display the results:
struct SearchResultsScreen: View {
#Environment(\.isSearching) private var isSearching
var results: [String]?
var body: some View {
if isSearching, let results {
if results.isEmpty {
Text("nothing to see here")
} else {
List(results, id: \.self) { fruit in
NavigationLink(destination: Text(fruit)) {
Text(fruit)
}
}
}
}
}
}
2. Let's have an ObservableObject to handle the logic:
class Search: ObservableObject {
static private let fruit = [
"Apples 🍏",
"Cherries 🍒",
"Pears 🍐",
"Oranges 🍊",
"Pineapples 🍍",
"Bananas 🍌"
]
#Published var text: String = ""
var results: [String]? {
if text.isEmpty {
return nil
} else {
return Self.fruit.filter({ $0.contains(text)})
}
}
}
3. And lastly lets declare the main screen where the search bar is displayed:
struct ContentView: View {
#StateObject var search = Search()
var body: some View {
NavigationView {
LinearGradient(colors: [.orange, .red], startPoint: .topLeading, endPoint: .bottomTrailing)
.overlay(SearchResultsScreen(results: search.results))
.searchable(text: $search.text)
.navigationTitle("Find that fruit")
}
}
}

How do I do drag and drop on a LazyVGrid using core data entities?

My end goal is to have a maneuverable list (like swiftui's native list) that reorders the position of items while you drag them.
I am trying to allow dragging and dropping of items in a LazyVGrid, but unlike the answer in SwiftUI | Using onDrag and onDrop to reorder Items within one single LazyGrid?, I am using Core Data, and therefore my array of items is not an observable object and therefore cannot be passed as an #Binding for easy reordering.
Here is what I have:
import SwiftUI
struct TopListTest: View {
#Environment(\.managedObjectContext) var context
#FetchRequest(sortDescriptors: [NSSortDescriptor(key: "order", ascending: true)])
var array: FetchedResults<Item> //An array of items pulled from Core Data
#State private var dragging: Item?
var body: some View {
NavigationView {
ZStack(alignment: .top) {
ScrollView {
LazyVGrid(columns: [GridItem(.adaptive(minimum: .greatestFiniteMagnitude))]) {
ForEach(array) { item in
listItemView(item: item)
.onDrag {
self.dragging = item
return NSItemProvider(object: String(item.order) as NSString)
}
.onDrop(of: ["Item"], delegate: DragRelocateDelegate(item: item, current: $dragging))
}
}
}
}
}
}
}
struct DragRelocateDelegate: DropDelegate {
//Where I would like to pass Core Data array, this would only be a copy, however
var item: Item
#Binding var current: Item?
func performDrop(info: DropInfo) -> Bool {
if item != current {
let from = current!.order
let to = item.order
if from != to {
item.order = from
current!.order = to
}
}
return true
}
}
struct listItemView: View {
var item: Item
var body: some View {
HStack {
Text("\(item.order)")
Spacer()
Text(item.name ?? "")
}
}
}
This code makes a simple list of core data entity Item which has an order which is just an id/position number and a name. This allows you to drag and drop items but it only swaps the position of two items and it does not automatically reorder as you drag like swiftui lists.

CoreData relation one-to-one can not display array of Tags belonging to each Listing [duplicate]

This question already has an answer here:
Swift 4 Core Data - Fetching Relationships
(1 answer)
Closed 1 year ago.
I have two entities Listing and Tags. The relation is working well and saveing to Core Data also.
class JSONViewModel: ObservableObject {
#Published var listings: [ListingModel] = []
// saving Json to Core Data...
func saveData(contex: NSManagedObjectContext) {
listings.forEach() { (data) in
let listingFetch: NSFetchRequest<Listing> = Listing.fetchRequest()
listingFetch.predicate = NSPredicate(format: "id = %#", "\(Int64(data.id))")
do {
let results:[Listing] = try contex.fetch(listingFetch)
if results.count == 0 {
let entity = Listing(context: contex)
entity.id = Int64(data.id)
entity.title = data.title
entity.name = data.name
entity.category = data.category
entity.permalink = data.permalink
data.tags.forEach { (tagData) in
let tags = Tag(context: contex)
tags.name = tagData
tags.toListing = entity
}
try? contex.save()
print ("Inserted Listing")
}
else
{
let entity = results[0]
entity.id = Int64(data.id)
entity.title = data.title
entity.name = data.name
entity.category = data.category
entity.permalink = data.permalink
data.tags.forEach { (tagData) in
let tag = Tag(context: contex)
tag.name = tagData
tag.toListing = entity
}
try? contex.save()
print ("Updated Listing: ID: \(entity.id); Title: \(String(describing: entity.title)); Tags: \(String(describing: data.tags))")
}
} catch let error as NSError {
print("error inserting / updating Listing \(error), \(error.userInfo)")
}
}
}
}
Printing after saveing the data is shown bellow.
Printscreen
So eatch Listing have an array of tags.
The problem is when i try to dispay them in the Lisiting detailed view i get an empty view.
I try to sort the tags belonging to the listing like this:
#FetchRequest(entity: Tag.entity(), sortDescriptors:
[NSSortDescriptor(keyPath: \Tag.name, ascending: false),],predicate: NSPredicate(format: "toListing == %#" , "Listing"))
var tags : FetchedResults<Tag>
And display it in the View like this:
ForEach(tags){ tag in
LazyVStack {
Text(tag.name!)
}
}
Core Data settings are bellow:
Listing Core Data printscreen
Tags Core Data printscreen
Following joakim-danielson sugestion i have learned that a related entity becomes a property of that entity.
My code looks like this now:
HStack {
let tags = Array(arrayLiteral: fetchedData!.toTag!)
ScrollView(.horizontal, showsIndicators: false, content: {
HStack(alignment: .center, spacing: 10) {
// ForEach(tags, id: \.self) { tag in // same result
ForEach(tags) { tag in
LazyHStack {
Text(fetchedData!.toTag!.name!)
}
}
}
})
}
Strangely i only get one tag displayed in the view:
printscreen

SwiftUI and Core Data: Using a fetch request with instance member as argument inside a view

I seem to be caught in a Catch-22 situation. Perhaps my approach is entirely wrong here. I hope someone can help. I want to create a star-based rating display using feedback from users who visit a particular real world landmark.
In CoreData I have an entity called Rating with attributes called rating (Int32) and landmark (String). I want to get the average for all rating(s) associated with a given landmark in order to display stars in the view for each.
Here is the code for the View:
struct TitleImageView: View {
#Environment(\.managedObjectContext) var viewContext : NSManagedObjectContext
let landmark: Landmark
var body: some View {
Image(landmark.imageName)
.resizable()
.shadow(radius: 10 )
.border(Color.white)
.scaledToFit()
.padding([.leading, .trailing], 40)
.layoutPriority(1)
.overlay(TextOverlay(landmark: landmark))
.overlay(RatingsOverlay(rating: stars))
}
}
Here is the fetch (which works as expected when the argument for the fetch is hard coded):
let fetchRequest = Rating.fetchRequestForLandmark(landmark: landmark.name)
var ratings: FetchedResults<Rating> {
fetchRequest.wrappedValue
}
var sum: Int32 {
ratings.map { $0.rating }.reduce(0, +)
}
var stars : Int32 {
sum / Int32(ratings.count)
}
The problem is this: When I insert the fetch before the body of the view, I get the warning
"Cannot use instance member 'landmark' within property initializer; property initializers run before 'self' is available"
When I place the fetch after the body, I get:
"Closure containing a declaration cannot be used with function builder 'ViewBuilder'" (with reference to var ratings)
Is there an easy way out of this conundrum or must I go back to the proverbial drawingboard? Thanks.
How about wrapping the fetch in a calculated property that returns a sum & stars tuple? Slightly different shape with the same results. Calculated properties can reference other properties, so the swift-init hurdle is cleared!
var metrics : (sum: Int, stars: Int) {
let fetchRequest = Rating.fetchRequestForLandmark(landmark: landmark.name)
var ratings: FetchedResults<Rating> {
fetchRequest.wrappedValue
}
let sum = ratings.map { $0.rating }.reduce(0, +)
let stars = sum / ratings.count
return (sum: sum, stars: stars)
}
Thanks to those who offered suggestions. After a long hiatus, I returned to this problem and arrived at this solution (based on a HackingWithSwift tutorial: https://www.hackingwithswift.com/books/ios-swiftui/dynamically-filtering-fetchrequest-with-swiftui)
Here's the code:
struct RatingsView: View {
var fetchRequest: FetchRequest<Rating>
var body: some View {
HStack(spacing: 0.4){
ForEach(1...5) { number in
if number > stars {
//Image(systemName: "star")
} else {
Image(systemName: "star.fill")
}
}
}
}
init(filter: String) {
fetchRequest = FetchRequest<Rating>(entity: Rating.entity() , sortDescriptors: [], predicate: NSPredicate(format: "%K == %#", "landmark" , filter))
}
var sum: Int16 {
fetchRequest.wrappedValue.reduce(0) { $0 + $1.rating }
}
var stars : Int {
var starCount:Int
if fetchRequest.wrappedValue.count > 0 {
starCount = Int(sum) / fetchRequest.wrappedValue.count
} else {
starCount = 0
}
return starCount
}
}
I'm not sure if this is the absolute best solution, but it's working as intended.
Hope this can help others.

SwiftUI reorder CoreData Objects in List

I want to change the order of the rows in a list that retrieves objects from the core data. Moving rows works, but the problem is that I can't save the changes. I don't know how to save the changed Index of the CoreData Object.
Here is my Code:
Core Data Class:
public class CoreItem: NSManagedObject, Identifiable{
#NSManaged public var name: String
}
extension CoreItem{
static func getAllCoreItems() -> NSFetchRequest <CoreItem> {
let request: NSFetchRequest<CoreItem> = CoreItem.fetchRequest() as! NSFetchRequest<CoreItem>
let sortDescriptor = NSSortDescriptor(key: "date", ascending: true)
request.sortDescriptors = [sortDescriptor]
return request
}
}
extension Collection where Element == CoreItem, Index == Int {
func move(set: IndexSet, to: Int, from managedObjectContext: NSManagedObjectContext) {
do {
try managedObjectContext.save()
} catch {
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
List:
struct CoreItemList: View {
#Environment(\.managedObjectContext) var managedObjectContext
#FetchRequest(fetchRequest: CoreItem.getAllCoreItems()) var CoreItems: FetchedResults<CoreItem>
var body: some View {
NavigationView{
List {
ForEach(CoreItems, id: \.self){
coreItem in
CoreItemRow(coreItem: coreItem)
}.onDelete {
IndexSet in let deleteItem = self.CoreItems[IndexSet.first!]
self.managedObjectContext.delete(deleteItem)
do {
try self.managedObjectContext.save()
} catch {
print(error)
}
}
.onMove {
self.CoreItems.move(set: $0, to: $1, from: self.managedObjectContext)
}
}
.navigationBarItems(trailing: EditButton())
}.navigationViewStyle(StackNavigationViewStyle())
}
}
Thank you for help.
Caveat: the answer below is untested, although I used parallel logic in a sample project and that project seems to be working.
There's a couple parts to the answer. As Joakim Danielson says, in order to persist the user's preferred order you will need to save the order in your CoreItem class. The revised class would look like:
public class CoreItem: NSManagedObject, Identifiable{
#NSManaged public var name: String
#NSManaged public var userOrder: Int16
}
The second part is to keep the items sorted based on the userOrder attribute. On initialization the userOrder would typically default to zero so it might be useful to also sort by name within userOrder. Assuming you want to do this, then in CoreItemList code:
#FetchRequest( entity: CoreItem.entity(),
sortDescriptors:
[
NSSortDescriptor(
keyPath: \CoreItem.userOrder,
ascending: true),
NSSortDescriptor(
keyPath:\CoreItem.name,
ascending: true )
]
) var coreItems: FetchedResults<CoreItem>
The third part is that you need to tell swiftui to permit the user to revise the order of the list. As you show in your example, this is done with the onMove modifier. In that modifier you perform the actions needed to re-order the list in the user's preferred sequence. For example, you could call a convenience function called move so the modifier would read:
.onMove( perform: move )
Your move function will be passed an IndexSet and an Int. The index set contains all the items in the FetchRequestResult that are to be moved (typically that is just one item). The Int indicates the position to which they should be moved. The logic would be:
private func move( from source: IndexSet, to destination: Int)
{
// Make an array of items from fetched results
var revisedItems: [ CoreItem ] = coreItems.map{ $0 }
// change the order of the items in the array
revisedItems.move(fromOffsets: source, toOffset: destination )
// update the userOrder attribute in revisedItems to
// persist the new order. This is done in reverse order
// to minimize changes to the indices.
for reverseIndex in stride( from: revisedItems.count - 1,
through: 0,
by: -1 )
{
revisedItems[ reverseIndex ].userOrder =
Int16( reverseIndex )
}
}
Technical reminder: the items stored in revisedItems are classes (i.e., by reference), so updating these items will necessarily update the items in the fetched results. The #FetchedResults wrapper will cause your user interface to reflect the new order.
Admittedly, I'm new to SwiftUI. There is likely to be a more elegant solution!
Paul Hudson (Hacking With Swift) has quite a bit more detail. Here is a link for info on moving data in a list. Here is a link for using core data with SwiftUI (it involves deleting items in a list, but is closely analogous to the onMove logic)
Below you can find a more generic approach to this problem. The algorithm minimises the number of CoreData entities that require an update, to the contrary of the accepted answer. My solution is inspired by the following article: https://www.appsdissected.com/order-core-data-entities-maximum-speed/
First I declare a protocol as follows to use with your model struct (or class):
protocol Sortable {
var sortOrder: Int { get set }
}
As an example, assume we have a SortItem model which implements our Sortable protocol, defined as:
struct SortItem: Identifiable, Sortable {
var id = UUID()
var title = ""
var sortOrder = 0
}
We also have a simple SwiftUI View with a related ViewModel defined as (stripped down version):
struct ItemsView: View {
#ObservedObject private(set) var viewModel: ViewModel
var body: some View {
NavigationView {
List {
ForEach(viewModel.items) { item in
Text(item.title)
}
.onMove(perform: viewModel.move(from:to:))
}
}
.navigationBarItems(trailing: EditButton())
}
}
extension ItemsView {
class ViewModel: ObservableObject {
#Published var items = [SortItem]()
func move(from source: IndexSet, to destination: Int) {
items.move(fromOffsets: source, toOffset: destination)
// Note: Code that updates CoreData goes here, see below
}
}
}
Before I continue to the algorithm, I want to note that the destination variable from the move function does not contain the new index when moving items down the list. Assuming that only a single item is moved, retrieving the new index (after the move is complete) can be achieved as follows:
func move(from source: IndexSet, to destination: Int) {
items.move(fromOffsets: source, toOffset: destination)
if let oldIndex = source.first, oldIndex != destination {
let newIndex = oldIndex < destination ? destination - 1 : destination
// Note: Code that updates CoreData goes here, see below
}
}
The algorithm itself is implemented as an extension to Array for the case that the Element is of the Sortable type. It consists of a recursive updateSortOrder function as well as a private helper function enclosingIndices which retrieves the indices that enclose around a certain index of the array, whilst remaining within the array bounds. The complete algorithm is as follows (explained below):
extension Array where Element: Sortable {
func updateSortOrder(around index: Int, for keyPath: WritableKeyPath<Element, Int> = \.sortOrder, spacing: Int = 32, offset: Int = 1, _ operation: #escaping (Int, Int) -> Void) {
if let enclosingIndices = enclosingIndices(around: index, offset: offset) {
if let leftIndex = enclosingIndices.first(where: { $0 != index }),
let rightIndex = enclosingIndices.last(where: { $0 != index }) {
let left = self[leftIndex][keyPath: keyPath]
let right = self[rightIndex][keyPath: keyPath]
if left != right && (right - left) % (offset * 2) == 0 {
let spacing = (right - left) / (offset * 2)
var sortOrder = left
for index in enclosingIndices.indices {
if self[index][keyPath: keyPath] != sortOrder {
operation(index, sortOrder)
}
sortOrder += spacing
}
} else {
updateSortOrder(around: index, for: keyPath, spacing: spacing, offset: offset + 1, operation)
}
}
} else {
for index in self.indices {
let sortOrder = index * spacing
if self[index][keyPath: keyPath] != sortOrder {
operation(index, sortOrder)
}
}
}
}
private func enclosingIndices(around index: Int, offset: Int) -> Range<Int>? {
guard self.count - 1 >= offset * 2 else { return nil }
var leftIndex = index - offset
var rightIndex = index + offset
while leftIndex < startIndex {
leftIndex += 1
rightIndex += 1
}
while rightIndex > endIndex - 1 {
leftIndex -= 1
rightIndex -= 1
}
return Range(leftIndex...rightIndex)
}
}
First, the enclosingIndices function. It returns an optional Range<Int>. The offset argument defines the distance for the enclosing indices left and right of the index argument. The guard ensures that the complete enclosing indices are contained within the array. Further, in case the offset goes beyond the startIndex or endIndex of the array, the enclosing indices will be shifted to the right or left, respectively. Hence, at the boundaries of the array, the index is not necessarily located in the middle of the enclosing indices.
Second, the updateSortOrder function. It requires at least the index around which the update of the sorting order should be started. This is the new index from the move function in the ViewModel. Further, the updateSortOrder expects an #escaping closure providing two integers, which will be explained below. All other arguments are optional. The keyPath is defaulted to \.sortOrder in conformance with the expectations from the protocol. However, it can be specified if the model parameter for sorting differs. The spacing argument defines the sort order spacing that is typically used. The larger this value, the more sort operations can be performed without requiring any other CoreData update except for the moved item. The offset argument should not really be touched and is used in the recursion of the function.
The function first requests the enclosingIndices. In case these are not found, which happens immediately when the array is smaller than three items or either inside one of the recursions of the updateSortOrder function when the offset is such that it would go beyond the boundaries of the array; then the sort order of all items in the array are reset in the else case. In that case, if the sortOrder differs from the items existing value, the #escaping closure is called. It's implementation will be discussed further below.
When the enclosingIndices are found, both the left and right index of the enclosing indices not being the index of the moved item are determined. With these indices known, the existing 'sort order' values for these indices are obtained through the keyPath. It is then verified if these values are not equal (which could occur if the items were added with equal sort orders in the array) as well as if a division of the difference between the sort orders and the number of enclosing indices minus the moved item would result in a non-integer value. This basically checks whether there is a place left for the moved item's potentially new sort order value within the minimum spacing of 1. If this is not the case, the enclosing indices should be expanded to the next higher offset and the algorithm run again, hence the recursive call to updateSortOrder in that case.
When all was successful, the new spacing should be determined for the items between the enclosing indices. Then all enclosing indices are looped through and each item's sorting order is compared to the potentially new sorting order. In case it changed, the #escaping closure is called. For the next item in the loop the sort order value is updated again.
This algorithm results in the minimum amount of callbacks to the #escaping closure. Since this only happens when an item's sort order really needs to be updated.
Finally, as you perhaps guessed, the actual callbacks to CoreData will be handled in the closure. With the algorithm defined, the ViewModel move function is then updated as follows:
func move(from source: IndexSet, to destination: Int) {
items.move(fromOffsets: source, toOffset: destination)
if let oldIndex = source.first, oldIndex != destination {
let newIndex = oldIndex < destination ? destination - 1 : destination
items.updateSortOrder(around: newIndex) { [weak self] (index, sortOrder) in
guard let self = self else { return }
var item = self.items[index]
item.sortOrder = sortOrder
// Note: Callback to interactor / service that updates CoreData goes here
}
}
}
Please let me know if you have any questions regarding this approach. I hope you like it.
Had a problem with Int16 and solved it by changing it to #NSManaged public var userOrder: NSNumber? and in the func: NSNumber(value: Int16( reverseIndex ))
As well I needed to add try? managedObjectContext.save() in the func to actually save the new order.
Now its working fine - thanks!
I'm not sure using a CoreData NSManagedObject for a view model object is the best approach, but if you do below is a sample for moving items in a SwiftUI List and persisting an object value based sort order.
An UndoManager is used in the event an error occurs during the move to rollback any changes.
class Note: NSManagedObject {
#nonobjc public class func fetchRequest() -> NSFetchRequest<Note> {
return NSFetchRequest<Note>(entityName: "Note")
}
#NSManaged public var id: UUID?
#NSManaged public var orderIndex: Int64
#NSManaged public var text: String?
}
struct ContentView: View {
#Environment(\.editMode) var editMode
#Environment(\.managedObjectContext) var viewContext
#FetchRequest(sortDescriptors:
[NSSortDescriptor(key: "orderIndex", ascending: true)],
animation: .default)
private var notes: FetchedResults<Note>
var body: some View {
NavigationView {
List {
ForEach (notes) { note in
Text(note.text ?? "")
}
}
.onMove(perform: moveNotes)
}
.navigationTitle("Notes")
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
EditButton()
}
}
}
func moveNotes(_ indexes: IndexSet, _ i: Int) {
guard
1 == indexes.count,
let from = indexes.first,
from != i
else { return }
var undo = viewContext.undoManager
var resetUndo = false
if undo == nil {
viewContext.undoManager = .init()
undo = viewContext.undoManager
resetUndo = true
}
defer {
if resetUndo {
viewContext.undoManager = nil
}
}
do {
try viewContext.performAndWait {
undo?.beginUndoGrouping()
let moving = notes[from]
if from > i { // moving up
notes[i..<from].forEach {
$0.orderIndex = $0.orderIndex + 1
}
moving.orderIndex = Int64(i)
}
if from < i { // moving down
notes[(from+1)..<i].forEach {
$0.orderIndex = $0.orderIndex - 1
}
moving.orderIndex = Int64(i)
}
undo?.endUndoGrouping()
try viewContext.save()
}
} catch {
undo?.endUndoGrouping()
viewContext.undo()
// TODO: something with the error
// set a state variable to display the error condition
fatalError(error.localizedDescription)
}
}
}
if do like this
.onMove {
self.CoreItems.move(set: $0, to: $1, from: self.managedObjectContext)
try? managedObjectContext.save()

Resources