iOS - 本地保存一组键值对

时间:2015-02-12 15:26:34

标签: ios swift nsobject nscoder

在我开发用户的应用程序中,需要添加一个" enterprise"使用该应用程序。但是,他们可以添加多个企业"到应用程序。每个添加的企业都需要两件事:名称和企业API密钥。

我创建了一个" Enterprise"类:

class Enterprise : NSObject {

    var name:String!
    var apiKey:String!

    init (name:String, apiKey:String) {
        self.name = name
        self.apiKey = apiKey
    }

    required init(coder decoder: NSCoder) {
        self.name = decoder.decodeObjectForKey("name") as String
        self.apiKey = decoder.decodeObjectForKey("apiKey") as String
        super.init()
    }

    func encodeWithCoder(coder: NSCoder) {
        coder.encodeObject(self.name, forKey: "name")
        coder.encodeObject(self.apiKey, forKey: "apiKey")
    }

}

关于这个类的一个注意事项,在我构建这个类的例子中,他们将该类分为NSCoder和NSObject,但是如果我添加" NSCoder"到了课堂,我收到以下错误:

  

来自班级的多重继承' NSObject'和' NSCoder'

使用以下内容保存数组时:

let name = self.enterpriseName.text
let key = self.apiKey.text
if name != "" {
    if key != "" {
        let defaults = NSUserDefaults.standardUserDefaults()
        let objectKey = "enterprise"
        var ent = [Enterprise(name: name, apiKey: key)]
        var entData = NSKeyedArchiver.archivedDataWithRootObject(ent)
        defaults.setObject(entData, forKey: objectKey)
        defaults.synchronize()
    }
    else {
        println("No API key")
    }
}
else {
    println("No name")
}

这在存储一个值时似乎有效,但是当我在启动时检查数组中有多少项时,它只显示1。

我有什么想法可以做到这一点?我正在寻找的最终结果将是:

Enterprises:
    Enterprise
        name: abc
        apiKey: 184nfh692j6j31))8dx

    Enterprise
        name: def
        apiKey: 23oih9823tng893g2gd

    Enterprise:
        name: ghi
        apiKey: sfgYSS4yw44gw31!#%q

如果用户选择删除特定企业,则可以从列表中删除。

修改

使用莱昂纳多(以下和接受的答案)方法,这是有效的:

let name = self.enterpriseName.text
let apiKey = self.apiKey.text
if name != "" {
    if apiKey != "" {
        var enterprises = NSMutableDictionary()
        var loadedEnterprises = Load.dictionary("enterprises")
        if loadedEnterprises != nil {
            if(loadedEnterprises.count > 0) {
                for (key, value) in loadedEnterprises {
                    enterprises.setObject(value, forKey: key as String)
                }
            }
        }
        enterprises.setObject(apiKey, forKey: name)     
        Save.dictionary("enterprises", enterprises)
    }
    else {
        println("No API key")
    }
}
else {
    println("No name")
}

2 个答案:

答案 0 :(得分:1)

您应该使用字典,否则您可能会使用不同的密钥来使用相同的企业。我创建了一个类来加载和保存字典到用户默认值。你应该这样做:

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)")
}

答案 1 :(得分:0)

您始终为'enterprise'Key覆盖'Enterprise',使用数组:

var entArray = defaults.objectForKey(objectKey)
entArray?.addObject(entData)
defaults.setObject(entArray, forKey: objectKey)

编辑:

适合我,但这不是一个好的解决方案:

func getEnterprise() {
    let objectKey = "enterprise"
    // get stored array
    let defaults = NSUserDefaults.standardUserDefaults()
    var array = defaults.objectForKey(objectKey) as? Array<NSData>
    if array != nil {
        for data in array! {
            var enterprise = NSKeyedUnarchiver.unarchiveObjectWithData(data) as? Enterprise
            println("\(enterprise!.name)")
        }
    }
}

func saveEnterprise() {
    let name = self.enterpriseName
    let key = self.apiKey
    if name != "" && name != nil {
        if key != "" && key != nil {
            let defaults = NSUserDefaults.standardUserDefaults()
            let objectKey = "enterprise"
            var ent = Enterprise(name: name!, apiKey: key!)

            // get stored array
            var array = defaults.objectForKey(objectKey) as? Array<NSData>
            if array == nil {
                array = Array()
            }
            var entData = NSKeyedArchiver.archivedDataWithRootObject(ent)
            array?.append(entData)
            defaults.setObject(array, forKey: objectKey)
            defaults.synchronize()
        }
        else {
            println("No API key")
        }
    }
    else {
        println("No name")
    }
}