iOS-在本地保存键值对数组 [英] iOS - Locally saving an array of key value pairs

查看:405
本文介绍了iOS-在本地保存键值对数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In an app I'm developing the user needs to add an "enterprise" to use the app. However, they can add more than one "enterprise" to the app. Every enterprise added needs two things: a name, and an enterprise API key.

我创建了一个"Enterprise"类:

I have created an "Enterprise" class:

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",则会出现以下错误:

One thing to note about this class, in the example I followed to build this class they have sub-classed the class as NSCoder as well as NSObject, however if I added "NSCoder" to the class, I get the following error:

从类'NSObject'和'NSCoder'的多重继承

Multiple inheritance from classes 'NSObject' and 'NSCoder'

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

When saving the array I'm using the following:

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.

This seems to work when storing one value, but when I check how many items are in the array at launch, it only shows 1.

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

Any ideas how I can do this? The end result I'm looking for would be something like:

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

    Enterprise
        name: def
        apiKey: 23oih9823tng893g2gd

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

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

With the ability to remove a particular enterprise from the list if the user choose to delete it.

编辑

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

Here's what worked, using Leonardo's (below, and accepted answer) method:

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

推荐答案

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

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

这篇关于iOS-在本地保存键值对数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆