|
| 1 | +// |
| 2 | +// NSManagedObjectContext+Utils.swift |
| 3 | +// DigitalAssortmentPlanner |
| 4 | +// |
| 5 | +// Created by Philipp Homann on 27.10.20. |
| 6 | +// Copyright © 2020 On Running. All rights reserved. |
| 7 | +// |
| 8 | +// Permission is hereby granted, free of charge, to any person obtaining a copy |
| 9 | +// of this software and associated documentation files (the "Software"), to deal |
| 10 | +// in the Software without restriction, including without limitation the rights |
| 11 | +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
| 12 | +// copies of the Software, and to permit persons to whom the Software is |
| 13 | +// furnished to do so, subject to the following conditions: |
| 14 | +// |
| 15 | +// The above copyright notice and this permission notice shall be included in |
| 16 | +// all copies or substantial portions of the Software. |
| 17 | +// |
| 18 | +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 19 | +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 20 | +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 21 | +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 22 | +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
| 23 | +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN |
| 24 | +// THE SOFTWARE. |
| 25 | + |
| 26 | + |
| 27 | +import Foundation |
| 28 | + |
| 29 | +import CoreData |
| 30 | + |
| 31 | +public extension NSManagedObjectContext { |
| 32 | + @discardableResult func saveIfNeeded(shouldReset : Bool = false) throws -> Bool { |
| 33 | + if self.hasChanges { |
| 34 | + try self.save() |
| 35 | + if shouldReset == true { |
| 36 | + self.reset() // Reset the context to clean up the cache and low the memory footprint. |
| 37 | + } |
| 38 | + return true |
| 39 | + } else { |
| 40 | + return false |
| 41 | + } |
| 42 | + } |
| 43 | +} |
| 44 | + |
| 45 | + |
| 46 | +/// allows you to use performAndWait with a throwing function in closure |
| 47 | +/// usage: try context.performAndWait { } |
| 48 | +public extension NSManagedObjectContext { |
| 49 | + func performAndWait<T>(_ block: () throws -> T) throws -> T { |
| 50 | + var result: Result<T, Error>? |
| 51 | + performAndWait { |
| 52 | + result = Result { try block() } |
| 53 | + } |
| 54 | + return try result!.get() |
| 55 | + } |
| 56 | + |
| 57 | + func performAndWait<T>(_ block: () -> T) -> T { |
| 58 | + var result: T? |
| 59 | + performAndWait { |
| 60 | + result = block() |
| 61 | + } |
| 62 | + return result! |
| 63 | + } |
| 64 | +} |
0 commit comments