Skip to content

Instantly share code, notes, and snippets.

@ZachOrr
Created March 11, 2019 01:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ZachOrr/a8d393f0005376a491e07da249690b03 to your computer and use it in GitHub Desktop.
Save ZachOrr/a8d393f0005376a491e07da249690b03 to your computer and use it in GitHub Desktop.
Way to update sorted/unsorted NSManagedObject relationship
extension NSManagedObject {
func updateToManyRelationship<T: NSManagedObject & Managed, J: SetInitable & SetGettable>(relationship: String, newValues new: [T]?, setClass: J) {
// Store our old values so we can reference them later
let oldSet = value(forKeyPath: relationship) as? J
let oldValues = oldSet?.items as? [T]
// The ol' switcharoo
let newSet = Set(new ?? [])
setValue(J(set: newSet), forKey: relationship)
// Clean up orphans, if applicable
if let oldValues = oldValues {
let oldSet = Set(oldValues)
oldSet.subtracting(newSet).filter({ $0.isOrphaned }).forEach({
managedObjectContext?.delete($0)
})
}
}
}
protocol SetInitable {
init(set: Set<AnyHashable>)
}
protocol SetGettable {
var items: [Any] { get }
}
extension NSSet: SetGettable {
var items: [Any] {
return allObjects
}
}
extension NSOrderedSet: SetGettable {
var items: [Any] {
return array
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment