我想在CoreData中存储CLLocationCoordinate2D对象。我在我的实体中创建了一个名为location
且属性为Transformable
的属性。我已经创建了一个NSManagedObject的子类,如下所示:
extension Task {
@nonobjc public class func fetchRequest() -> NSFetchRequest<Task> {
return NSFetchRequest<Task>(entityName: "Task");
}
@NSManaged public var name: String?
@NSManaged public var location: CLLocationCoordinate2D
}
但是当我想设置属性时会抛出错误
let task = Task(context: context)
task.name = "Hello"
task.location = CLLocationCoordinate2D(latitude: CLLocationDegrees(10), longitude: CLLocationDegrees(12))
这里出现错误信息:
2016-12-24 11:50:27.425833 CoreDataTodo[839:273413] [error] error: Property 'setLocation:' is a scalar type on class 'Task' that does not match its Entity's property's scalar type. Dynamically generated accessors do not support implicit type coercion. Cannot generate a setter method for it.
CoreData: error: Property 'setLocation:' is a scalar type on class 'Task' that does not match its Entity's property's scalar type. Dynamically generated accessors do not support implicit type coercion. Cannot generate a setter method for it.
2016-12-24 11:50:27.426143 CoreDataTodo[839:273413] -[Task setLocation:]: unrecognized selector sent to instance 0x1766eca0
2016-12-24 11:50:27.426780 CoreDataTodo[839:273413] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[Task setLocation:]: unrecognized selector sent to instance 0x1766eca0'
*** First throw call stack:
(0x1c5a0df7 0x1b803077 0x1c5a6505 0x1c5a4579 0x1c4c93d8 0x4b8cc 0x4bd60 0x21681ee5 0x21681e73 0x2166bf97 0x2168179b 0x216812e7 0x2167bee7 0x2164ccf5 0x21de898d 0x21de25d3 0x1c55c71b 0x1c55c225 0x1c55a4fb 0x1c4a9533 0x1c4a9341 0x1dc80bfd 0x216b7e27 0x216b2551 0x4f520 0x1bc7350b)
libc++abi.dylib: terminating with uncaught exception of type NSException
答案 0 :(得分:1)
要使用可转换属性,您需要以下其中一项:
NSCoding
的属性类型。 CLLocationCoordinate2D
没有,部分原因是只有类可以符合。这就是那些错误消息试图解释的内容。NSValueTransformer
的自定义子类,可以在数据类型和NSData
之间进行转换。您可以使用第二个选项。但是,将纬度和经度值分别存储为自己的属性会更容易。然后为您的子类添加一个方便的方法,将它们组合起来并返回CLLocationCoordinate2D
。