gpt4 book ai didi

ios - 显然,CLLocation 对象不能精确地归档/取消归档

转载 作者:行者123 更新时间:2023-11-28 21:01:40 30 4
gpt4 key购买 nike

在我的应用程序中(只显示相关代码),我有一个类 Test 有一个属性

var location: CLLocation  

我使用

存档它
public func encode(with aCoder: NSCoder) {
aCoder.encode(location, forKey: "location")
}

并且使用

取消存档
required convenience public init?(coder aDecoder: NSCoder) {
let unarchivedLocation = aDecoder.decodeObject(forKey: "location") as! CLLocation
self.init(location: unarchivedLocation)
}

单元测试使用

func test_archiningUnarchiving() {
// given
let location = CLLocation.init(latitude: 0.0, longitude: 0.0)
let test = Test(location: location)
// when
let data = NSKeyedArchiver.archivedData(withRootObject: test)
let unarchivedTest = NSKeyedUnarchiver.unarchiveObject(with: data) as? Test
// then
XCTAssertEqual(unarchivedTest!.location, location, "location was not correctly unarchived")
}

此测试失败:

XCTAssertEqual failed: ("<+0.00000000,+0.00000000> +/- 0.00m (speed -1.00 mps / course -1.00) @ 1/19/18, 3:30:50 PM Central European Standard Time") is not equal to ("<+0.00000000,+0.00000000> +/- 0.00m (speed -1.00 mps / course -1.00) @ 1/19/18, 3:30:50 PM Central European Standard Time") - location was not correctly unarchived

日志显示原始位置和未存档位置两次完全相同的数据。
知道可能出了什么问题吗??

最佳答案

问题不在于归档,而在于相等性测试。如果您比较两个不同的 CLLocation 实例,即使它们相同,它也将始终返回 false

最重要的是,任何未显式实现 isEqual:NSObject 子类(例如 CLLocation 的情况)都会遇到这种情况行为。

Using Swift with Cocoa and Objective-C: Interacting with Objective-C APIs说:

Swift provides default implementations of the == and === operators and adopts the Equatable protocol for objects that derive from the NSObject class. The default implementation of the == operator invokes the isEqual: method ... You should not override the equality or identity operators for types imported from Objective-C.

而且,Concepts in Objective-C Programming: Introspection告诉我们:

The default NSObject implementation of isEqual: simply checks for pointer equality.

就个人而言,我希望 NSObject 子类不会自动继承 isEqual:,但事实就是如此。

最重要的是,不要尝试测试 NSObject 子类的相等性,除非您知道它已正确实现 isEqual: 覆盖。如果你愿意,写你自己的方法,例如isEqual(to location: CLLocation)(但不是 isEqual(_:))执行两个 CLLocation 对象的成员比较。

关于ios - 显然,CLLocation 对象不能精确地归档/取消归档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48343477/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com