【问题标题】:Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** setObjectForKey: object cannot be nil (key: index)'由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“*** setObjectForKey: object cannot be nil (key: index)”
【发布时间】:2017-07-06 11:22:06
【问题描述】:

我正在开发一个自动完成文本字段,这发生了

NSString *substring = [NSString stringWithString:autocompleteTextField.text];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@" CityCode[c] contains %@ OR Zone[c] contains %@ ",substring,substring];
filteredarr =[[searchArray filteredArrayUsingPredicate:predicate] copy];

错误发生在行

filteredarr =[[searchArray filteredArrayUsingPredicate:predicate] 复制];

filteredarr 是一个数组 searcharray 是一个获取 json 数据的数组

请帮帮我 提前致谢

【问题讨论】:

  • 看起来你的子字符串是空的。
  • 子字符串不为空...但是在发送到空数组时出现问题
  • 是的,因为您试图在数组中添加任何内容,因此出现错误。您需要检查 [searchArray filteredArrayUsingPredicate:predicate] 是否返回某些内容,并且只检查 filteredarr 中的 copy
  • CityCode contains[c] %@ OR Zone contains[c] %@ 代替?这似乎解决了它,但我不知道为什么exaclty。我猜想,不知何故,它可能在CityCode 上使用subscriptc,以及为什么你会得到一个“setObject:ForKey:”而为零。
  • 谢谢@Larme。那行得通。你是救生员

标签: ios objective-c nsstring nspredicate predicate


【解决方案1】:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@" CityCode[c] contains %@ OR Zone[c] contains %@ ",substring,substring];

您需要将[c](不区分大小写)放在保留字contains 之后,而不是key 之后

=>

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"CityCode contains[c] %@ OR Zone contains[c] %@ ",substring,substring];

对于错误本身(消息不是很明确),我想这就是为什么尝试使用 c 键在 CityCodeZone 上下标,得到 nil,这就是为什么你得到一个 setObject:forKey:出现 nil 错误(您不能将 nil 值放在对象上)。

为了习惯,我喜欢把保留谓词写成大写,如果是保留词并且有“动作”=>CONTAINS[c],会更容易阅读,但这只是我的口味。

【讨论】:

    猜你喜欢
    • 2015-07-27
    • 2018-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多