且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

iOS-在本地保存键值对数组

更新时间:2023-02-02 20:35:08

您应该使用字典,否则您最终可能会使用不同的密钥进入同一家企业.我创建了一个类来加载和保存字典到用户默认值.您应该执行以下操作:

You should use a Dictionary otherwise you may end up with the same enterprise with different keys. I have created a class to load and save dictionaries to the user default. You should do as follow:

class Load {
    class func dictionary(key:String) -> NSDictionary! {
        return NSUserDefaults.standardUserDefaults().objectForKey(key) as? NSDictionary
    }
}

class Save {
    class func dictionary(key:String, _ value:NSDictionary) {
        NSUserDefaults.standardUserDefaults().setObject(value, forKey: key)
    }
}

class Remove {
    class func object(key:String) {
        NSUserDefaults.standardUserDefaults().removeObjectForKey(key)
    }
}


var enterprises:[String:String] = ["abc":"184nfh692j6j31))8dx","def":"23oih9823tng893g2gd","ghi":"sfgYSS4yw44gw31!#%q"]
Save.dictionary("enterprises", enterprises)

name = "jkl"
apiKey = "9a4giNifjKJq6v8G4fb"

if !name.isEmpty {
    if !apiKey.isEmpty {
        enterprises[name] = apiKey
        Save.dictionary("enterprises", enterprises)
    } else {
        println("No API key")
    }
} else {
    println("No name")
}

for (key, value) in enterprises {
    println("\(key)=\(value)")
}

let loadedDictionary = Load.dictionary("enterprises")

for (key, value) in loadedDictionary {
    println("\(key)=\(value)")
}