我有将一些 json 反序列化为对象的代码。此代码在 iPhone 5s、iPhone 6 和 iPhone 6+ 上运行良好。
但是,在 iPhone 5 或 iPhone 4s 上运行时,出现错误:[__NSCFString longValue]: unrecognized selector sent to instance
代码如下:
public class Serializable : NSObject
{
func deserialize(dictionary: NSMutableDictionary)
{
/* Remove entries from the dictionary that do not have a corresponding property on the target object.
By default, setValuesForKeysWithDictionary() will cause the app to crash if it encounters the above. */
removeInvalidProperties(self, dictionary: dictionary)
self.setValuesForKeysWithDictionary(dictionary)
}
private func removeInvalidProperties(object: NSObject, dictionary: NSMutableDictionary)
{
for key in dictionary.allKeys {
var exists: Bool = object.respondsToSelector(Selector(key as String))
if !exists {
dictionary.removeObjectForKey(key)
}
}
}
}
我不禁注意到,正确运行此代码的手机是 64 位架构,而抛出错误的是 32 位架构。我只能假设这是一个运行时兼容性问题。
有谁知道可能是什么原因造成的,或者如何解决这个问题?
最佳答案
可能出现的一个问题是,如果您在从 JSON 反序列化时输入错误的属性。我非常有信心 64 位运行时会自动将字符串转换为 int,但 32 位运行时不会。
关于iOS 8 setValuesForKeysWithDictionary 在 iPhone 5/iPhone 4s 上失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27449287/