【问题标题】:RestKit RKObjectMapping Swift OptionalRestKit RKObjectMapping Swift 可选
【发布时间】: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)。

标签: ios swift restkit


【解决方案1】:

让您的财产dynamic

dynamic var coordinate: CLLocationCoordinate2D?

【讨论】:

    【解决方案2】:

    在我看来,您的应用会因为这行而崩溃

    let mapping = RKObjectMapping(forClass: self) let coordinateMapping = RKAttributeMapping(fromKeyPath: "coordinate", toKeyPath: "coordinate")

    您想映射一个可选的属性/变量,但在您调用 objectMapping() 时,您的 coordinate 可能为零。

    你有没有尝试过这样的事情:

    import MapKit
    
    class Activity: NSObject {
    
        var coordinate: CLLocationCoordinate2D?
    
        class func objectMapping() -> RKObjectMapping {
    
            if let c = self. coordinate {
                 let mapping = RKObjectMapping(forClass: self)
    
                 let coordinateMapping = RKAttributeMapping(fromKeyPath: "coordinate", toKeyPath: "coordinate")
                 coordinateMapping.valueTransformer = RKCLLocationCoordinate2DValueTransformer()
                 mapping.addPropertyMapping(coordinateMapping)
    
                 return mapping
            }
            return nil
        }
    }
    

    我不确定这是否有效,但我猜let mapping = RKObjectMapping(forClass: self) 正在尝试映射您的整个班级Activity,这会使您的代码崩溃,而此时未设置coordinate

    【讨论】:

    • objectMapping 是一个类函数。 coordinate 在这种情况下永远不会有值。
    猜你喜欢
    • 2011-12-22
    • 1970-01-01
    • 2014-02-08
    • 1970-01-01
    • 2012-04-30
    • 1970-01-01
    • 2014-03-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多