【发布时间】:2015-05-05 16:24:51
【问题描述】:
我有一个名为Activity 的快速模型,可以选择附加一个coordinate。
import MapKit
class Activity: NSObject {
var coordinate: CLLocationCoordinate2D?
class func objectMapping() -> RKObjectMapping {
let mapping = RKObjectMapping(forClass: self)
let coordinateMapping = RKAttributeMapping(fromKeyPath: "coordinate", toKeyPath: "coordinate")
coordinateMapping.valueTransformer = RKCLLocationCoordinate2DValueTransformer()
mapping.addPropertyMapping(coordinateMapping)
return mapping
}
}
当启动我的应用程序时,这给了我:
2015-05-05 12:14:30.741 Sample[54338:531558] *** 由于未捕获的异常“NSUnknownKeyException”而终止应用程序,原因:“[setValue:forUndefinedKey:]:此类不是键值编码-符合关键坐标。'
如果我将 coordinate 更改为非可选并提供应用程序运行的默认值。
所以我的问题是我如何快速使用 RestKit 来处理 Optionals?
【问题讨论】:
-
当它是一个普通数字时,为什么你希望它是可选的?如果它们是可选的,则编译器可能不会为属性生成访问器......
-
并非所有活动都有附加的纬度和经度,所以我认为它会成为可选的。我明白你对常规数字的看法,但我可以对更复杂的问题提出同样的问题,比如
CLLocationCoordinate2D -
我从未使用过 RestKit,所以我不确定内部工作原理......但是,我浏览了源代码并在
RKAttributeMapping(@987654327) 的初始化程序的实现中发现了这一点@)... 初始化程序中的第一行代码是:NSAssert(sourceKeyPath || destinationKeyPath, @"Both the source and destination key paths cannot be nil");。对我来说,这意味着崩溃是因为coordinate是可选的(因此nil)和coordinate用于两个键路径(因此两者都是nil)。