在 Swift 中编码 CLLocation 数组会使编译器崩溃?

Posted

技术标签:

【中文标题】在 Swift 中编码 CLLocation 数组会使编译器崩溃?【英文标题】:Encoding an array of CLLocation in Swift crashes the compiler? 【发布时间】:2014-07-04 02:57:49 【问题描述】:

我有一个似乎可以正常工作的 Swift 类,除非我尝试实现 NSCoding。似乎给我一个问题的行是:

        aCoder.encodeObject(runSamples, forKey: "runSamples")

如果我将这一行注释掉,一切都会正常编译。但是,在 Xcode 中取消注释会导致:

Bitcast 要求两个操作数都是指针或两者都不是 %201 = bitcast i32 %200 到 %objc_object*, !dbg !241 LLVM 错误:发现损坏的函数,编译中止! 命令 /Applications/Xcode6-Beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift 失败,退出代码为 1

取消注释 Playground 行只会导致应用崩溃。

我认为这是一个编译器问题,但我想看看在向 Apple 报告之前是否有明显遗漏的东西。

全班:

class RunRecord: NSObject 
    let startDate: NSDate
    var endDate: NSDate?
    var runSamples: CLLocation[]

    var currentSpeed: CLLocationDistance 
    return self.runSamples[runSamples.endIndex - 1].speed
    

    init(startDate: NSDate) 
        self.startDate = startDate
        self.runSamples = CLLocation[]()
        super.init()
    

    init(coder aDecoder: NSCoder!) 
        startDate = aDecoder.decodeObjectForKey("startDate") as NSDate
        endDate = aDecoder.decodeObjectForKey("endDate") as? NSDate
        runSamples = aDecoder.decodeObjectForKey("runSamples") as CLLocation[]
    

    func encodeWithCoder(aCoder: NSCoder!) 
        aCoder.encodeObject(startDate, forKey: "startDate")
        aCoder.encodeObject(endDate, forKey: "endDate")
        aCoder.encodeObject(runSamples, forKey: "runSamples")
    

    func addSample(sample: CLLocation) 
        runSamples.append(sample)
    

【问题讨论】:

你怎么称呼它?也就是说,在调用 encodeWithCoder 之前如何初始化 NSCoder?它在我的操场上运行良好 - 我正在使用 NSKeyedArchiver(forWritingWithMutableData:) 据我所知,这是编译器崩溃了,这意味着我什至没有机会运行它。 【参考方案1】:

看起来问题在于 Swift 数组被自动桥接到了 Objective-C。这解决了问题:

aCoder.encodeObject(runSamples.bridgeToObjectiveC(), forKey: "runSamples")

【讨论】:

以上是关于在 Swift 中编码 CLLocation 数组会使编译器崩溃?的主要内容,如果未能解决你的问题,请参考以下文章

在 [CLLocation] SWIFT 中保存 JSON 结果

在 Swift 中将 CLLocation 转换为 MKMapItem

在 CoreData 中保存 Swift CLLocation

如果 Swift 中存在 NSUserDefault,则尝试更新 CLLocation

如何获得顺序 MKDirection 请求响应 Swift

无法在 swift 中使用 CLPlacemark 获取 subLocality