问题描述
我想在CoreData中存储一个CLLocationCoordinate2D对象.我在实体中创建了一个名为 location
的属性,其类型为 Transformable
.我创建了一个NSManagedObject的子类,如下所示:
I want to store a CLLocationCoordinate2D Object in CoreData. I've created an attribute in my entity called location
with type Transformable
. I've created a subclass of NSManagedObject which looks like this:
extension Task {
@nonobjc public class func fetchRequest() -> NSFetchRequest<Task> {
return NSFetchRequest<Task>(entityName: "Task");
}
@NSManaged public var name: String?
@NSManaged public var location: CLLocationCoordinate2D
}
但是当我想设置属性时会抛出错误
But when I want to set the attribute it throws an error
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
推荐答案
要使用可转换属性,您需要以下条件之一:
To use a transformable attribute, you need one of the following:
- 符合
NSCoding
的属性类型.CLLocationCoordinate2D
不能,部分原因是只有类可以符合要求.这就是这些错误消息试图解释的内容. -
NSValueTransformer
的自定义子类,可以在数据类型和NSData
之间进行转换.
- An Attribute type that conforms to
NSCoding
.CLLocationCoordinate2D
does not, in part because only classes can conform. This is what those error messages are trying to explain. - A custom subclass of
NSValueTransformer
that can convert between the data type andNSData
.
您可以使用第二个选项.但是,将纬度和经度值分别存储为自己的属性会更容易.然后,将便利方法添加到您的子类中,将它们组合在一起并返回 CLLocationCoordinate2D
.
You could use the second option. But it'd be easier to store the latitude and longitude values separately as their own attributes. Then add a convenience method to your subclass that combines them and returns a CLLocationCoordinate2D
.
这篇关于将CLLocationCoordinate2D存储在CoreData中可转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!