加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Swift iOS NSDictionary setValue崩溃 – 但为什么呢?

发布时间:2020-12-14 04:42:30 所属栏目:百科 来源:网络整理
导读:我有这个代码(从另一种语言移植,因此有一些不同的命名约定,但现在请忍受这个) var FDefaultsList: NSDictionary = [String:String]();let TmpKey: String = TmpKeyValue[0];let TmpValue: String = TmpKeyValue[1]; if (TmpKey != "") (TmpValue != "") { //
我有这个代码(从另一种语言移植,因此有一些不同的命名约定,但现在请忍受这个)

var FDefaultsList: NSDictionary = [String:String]();
let TmpKey: String = TmpKeyValue[0];
let TmpValue: String = TmpKeyValue[1];    
if (TmpKey != "") && (TmpValue != "") {
  //let TmpAnyObjectValue: AnyObject? = TmpValue;
  //FDefaultsList.setValue(TmpAnyObjectValue,forKey: TmpKey);
  FDefaultsList.setValue(TmpValue,forKey: TmpKey);
}

但是,无论我使用哪个setValue变体,对setValue的调用都会抛出一个错误(据我所知无意义)并退出app(Xcode编辑器被带到AppDelegate类:UIResponder,UIApplicationDelegate)

我猜我使用NSDictionary错了?我试图在文本文件中读取每行是key = value字符串

解决方法

您应该声明一个实际的NSMutableDictionary而不是转换为NSDictionary.

并且您可以使用比setValue(实际上应该是setObject)更简单的下标:

var FDefaultsList = NSMutableDictionary()
let TmpKey: String = "a"
let TmpValue: String = "b"
if TmpKey != "" && TmpValue != "" {
    FDefaultsList[TmpValue] = TmpKey
}

一个更“Swifty”的版本可能是:

var defaultsList = [String:String]()
let tmpKey = "a"
let tmpValue = "b"
if !tmpKey.isEmpty && !tmpValue.isEmpty {
    defaultsList[tmpValue] = tmpKey
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读