You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Firestore setData时触发Unrecognized Selector异常求助

解决Firestore setData时的NSInvalidArgumentException报错

这个报错的核心原因很明确:Firestore iOS SDK在处理字典键时,错误地将Int类型的键当成NSString类型调用了hasPrefix:方法,而Swift的Int桥接到OC后是NSCFNumber,这个类并没有hasPrefix:方法,所以直接触发了崩溃。

虽然Firestore控制台显示支持[Int: Timestamp]类型的字段,但SDK层面目前对字典键的类型有严格要求——它只接受String(OC里的NSString)作为键。你的customObjectTwo是[Int: Date]类型,Int作为键就刚好踩中了这个坑。

解决方案:将Int键转换为String

你只需要把[Int: Date]转换成[String: Date],把字典里的Int键转成String即可,示例代码如下:

// 转换customObjectTwo的键为String类型
let convertedCustomObjectTwo = customObjectTwo.reduce(into: [String: Date]()) { result, pair in
    result[String(pair.key)] = pair.value
}

// 使用转换后的字典调用setData
db.collection("collection").document("document").setData([
    "y": customObjectOne,
    "z": convertedCustomObjectTwo
], options: SetOptions.merge())

如果想更明确地控制Date转Timestamp的过程,也可以手动转换:

let timestampDict = customObjectTwo.reduce(into: [String: Timestamp]()) { result, pair in
    result[String(pair.key)] = Timestamp(date: pair.value)
}

补充说明

Firestore后端确实支持整数类型的键,但iOS SDK在解析传入的字典时,会默认把键当作字符串处理。当你传入非String类型的键时,SDK内部的类型判断逻辑会出现异常,导致调用错误的方法。转换键的类型后,SDK就能正常识别并处理你的数据了,Date也会自动被转换为Firestore的Timestamp类型存储。

内容的提问来源于stack exchange,提问作者Chris

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:03:58