ManagedObjectAdapter is a lightweight adapter for the converts between Model instances and Core Data managed objects.
Specify "ManagedObjectAdapter" in your Cartfile
:
github "teambition/ManagedObjectAdapter"
Models that you want to use ManagedObjectAdapter must be a subclass of NSObject
and conform to ManagedObjectSerializing
protocol.
protocol ManagedObjectSerializing {
static func managedObjectEntityName() -> String
static func managedObjectKeysByPropertyKey() -> [String: String]
static func valueTransformersByPropertyKey() -> [String: ValueTransformer]
static func relationshipModelClassesByPropertyKey() -> [String: AnyClass]
static func propertyKeysForManagedObjectUniquing() -> Set<String>
}
You can use ManagedObjectAdapter like this:
@objcMembers
class TestModel: NSObject, ManagedObjectSerializing {
var id: String?
// Property name of this property in xcdatamodeld is "downloadUrl"
var downloadURL: URL?
// Type of this property in xcdatamodeld is Transformable
var transformableModel: TransformableModel?
// Type of this property in xcdatamodeld is to many relationship
var relationshipModels: Set<RelationshipModel>?
required override init() { }
static func managedObjectKeysByPropertyKey() -> [String: String] {
return ["downloadURL": "downloadUrl"]
}
static func valueTransformersByPropertyKey() -> [String: ValueTransformer] {
return ["transformableModel": TransformableModelTransformer()]
}
static func propertyKeysForManagedObjectUniquing() -> Set<String> {
return ["id"]
}
static func relationshipModelClassesByPropertyKey() -> [String: AnyClass] {
return ["relationshipModels": RelationshipModel.self]
}
}
class TransformableModel: NSObject, ManagedObjectSerializing {
var id: String?
required override init() { }
}
class RelationshipModel: NSObject, ManagedObjectSerializing {
var id: String?
required override init() { }
}
class TransformableModelTransformer: ValueTransformer {
override func transformedValue(_ value: Any?) -> Any? {
// Model to Data
}
override func reverseTransformedValue(_ value: Any?) -> Any? {
// Data to Model
}
}
let managedObjectContext = ...
let originModel = ...
let moTestModel = originModel.toManagedObject(in: managedObjectContext)
let testModel = TestModel.model(from: moTestModel!)
iOS 8.0
ManagedObjectAdapter is released under the MIT license. See LICENSE for details.
Have a question? Please open an issue!