This repository has been archived by the owner on Oct 10, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CoreDataModelable.swift
58 lines (45 loc) · 2.43 KB
/
CoreDataModelable.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
//
// Created by Dariusz Rybicki on 15/04/16.
//
import BNRCoreDataStack
extension CoreDataModelable where Self: NSManagedObject {
// MARK: - Creating Objects
/**
Creates a new instance of the Entity within the specified `NSManagedObjectContext` and configures it using provided closure.
- parameter context: `NSManagedObjectContext` to create object within.
- parameter configure: A closure that configures new entity.
returns: `[Self]`: The array of updated entities.
*/
static public func createInContext(context: NSManagedObjectContext, @noescape configure: Self -> ()) -> Self {
let entity = self.init(managedObjectContext: context)
configure(entity)
return entity
}
// MARK: - Updating Objects
/**
Updates Entities that matches the optional predicate within the specified `NSManagedObjectContext` using provided closure.
- parameter context: `NSManagedObjectContext` to update objects within.
- parameter predicate: An optional `NSPredicate` for filtering.
- parameter configure: A closure that updates each of the entities.
returns: `[Self]`: The array of updated entities.
*/
static public func updateInContext(context: NSManagedObjectContext, predicate: NSPredicate?, @noescape configure: Self -> ()) throws -> [Self] {
return try allInContext(context, predicate: predicate).map {
configure($0)
return $0
}
}
/**
Updates Entities that matches the optional predicate or (if there are no such Entities) creates a new Entity and configures it using provided closure.
- parameter context: `NSManagedObjectContext` to update or create objects within.
- parameter predicate: An optional `NSPredicate` for filtering.
- parameter configure: A closure that updates existing entities or configures new entity.
returns: `[Self]`: The array of updated entities or array with created entity.
*/
static public func updateOrCreateInContext(context: NSManagedObjectContext, predicate: NSPredicate?, @noescape configure: Self -> ()) throws -> [Self] {
let updatedEntities = try updateInContext(context, predicate: predicate, configure: configure)
guard updatedEntities.count == 0 else { return updatedEntities }
let insertedEntity = createInContext(context, configure: configure)
return [insertedEntity]
}
}