-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathPersistenceController+Photo.swift
69 lines (60 loc) · 2.34 KB
/
PersistenceController+Photo.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
59
60
61
62
63
64
65
66
67
68
69
/*
<samplecode>
<abstract>
An extension that wraps the methods related to the Photo entity.
</abstract>
</samplecode>
*/
import Foundation
import CoreData
// MARK: - Convenient methods for managing photos.
//
extension PersistenceController {
func addPhoto(photoData: Data, thumbnailData: Data, tagNames: [String] = [], context: NSManagedObjectContext) {
context.perform {
let photo = Photo(context: context)
photo.uniqueName = UUID().uuidString
let thumbnail = Thumbnail(context: context)
thumbnail.data = thumbnailData
thumbnail.photo = photo
let photoDataObject = PhotoData(context: context)
photoDataObject.data = photoData
photoDataObject.photo = photo
for tagName in tagNames {
let existingTag = Tag.tagIfExists(with: tagName, context: context)
let tag = existingTag ?? Tag(context: context)
tag.name = tagName
tag.addToPhotos(photo)
}
context.save(with: .addPhoto)
}
}
func delete(photo: Photo) {
if let context = photo.managedObjectContext {
context.perform {
context.delete(photo)
context.save(with: .deletePhoto)
}
}
}
func photoTransactions(from notification: Notification) -> [NSPersistentHistoryTransaction] {
var results = [NSPersistentHistoryTransaction]()
if let transactions = notification.userInfo?[UserInfoKey.transactions] as? [NSPersistentHistoryTransaction] {
let photoEntityName = Photo.entity().name
for transaction in transactions where transaction.changes != nil {
for change in transaction.changes! where change.changedObjectID.entity.name == photoEntityName {
results.append(transaction)
break // Jump to the next transaction.
}
}
}
return results
}
func mergeTransactions(_ transactions: [NSPersistentHistoryTransaction], to context: NSManagedObjectContext) {
context.perform {
for transaction in transactions {
context.mergeChanges(fromContextDidSave: transaction.objectIDNotification())
}
}
}
}