简体   繁体   English

如何使用 NSUserDefault 将 NSArray 存储在 NSDictionary 中

[英]How to store NSArray in NSDictionary with NSUserDefault

First of all I want to say that I am new in iOS.首先我想说我是 iOS 新手。 I am facing a problem.我面临一个问题。 I've tried many things but have not achieved any success.我尝试了很多东西,但没有取得任何成功。 In my app I declared a NSDictionay in my .pch file like so:在我的应用程序中,我在.pch文件中声明了一个NSDictionay ,如下所示:

#define Default_InCategory @{@[@"Other",@"other_icon.png"], @[@"Salary",@"salary_icon.png"]]} 

These are some default values for a category.这些是类别的一些默认值。 I also have an option from which the user can add custom values in this category.我还有一个选项,用户可以从中在此类别中添加自定义值。 Due to some restrictions I am storing New Custom category in another separate key with name Custom_InCategory same as the above format.由于一些限制,我将New Custom类别存储在另一个单独的键中,名称为Custom_InCategory ,与上述格式相同。 But I have not achieved any success.但是我没有取得任何成功。 I am trying with the below code:我正在尝试使用以下代码:

#define USERDEFAULT [NSUserDefaults standardUserDefaults]

NSMutableDictionary *tempDic =[[NSMutableDictionary alloc]initWithDictionary:[USERDEFAULT objectForKey:Custom_InCategory]];

NSArray *tempArr =@[@"CategoryName",@"imageName"];

[tempDic setObject:tempArr forKey:@"newCat"];

[USERDEFAULT setObject:tempDic Custom_InCategory];
[USERDEFAULT synchronize];

If you're going to store single key-value paired dictionary then we can directly store in UserDefaults.如果您要存储单个键值对字典,那么我们可以直接存储在 UserDefaults 中。

If your dictionary is collection of dictionaries then it will throw an error while storing.如果您的字典是字典的集合,那么它会在存储时抛出错误。

For that situation, you need to Archive your Dictionary into data and then store it to UserDefaults.对于这种情况,您需要将您的 Dictionary 存档到数据中,然后将其存储到 UserDefaults。 When you need the dictionary, then Unarchive the data back to Dictionary as following:当您需要字典时,然后将数据解档回字典,如下所示:

Archive Dictionary to Data:将字典存档到数据:

NSData *data = [NSKeyedArchiver archivedDataWithRootObject:yourDictionary];

Store this Data to UserDefaults as following:将此数据存储到 UserDefaults,如下所示:

[[NSUserDefaults standardUserDefaults]setObject:data forKey:@"yourData"];

Get the Data from UserDefaults:从 UserDefaults 获取数据:

NSData *archivedData = [[NSUserDefaults standardUserDefaults]objectForKey:@"yourData"];

Unarchive Dictionary from Data:从数据中取消归档字典:

NSDictionary *dictionary = [NSKeyedUnarchiver unarchiveObjectWithData:archivedData];

Hope it helps..希望能帮助到你..

This code works fine:此代码工作正常:

NSMutableDictionary *tempDic = [[NSMutableDictionary alloc]init];
NSArray *tempArr =@[@"CategoryName",@"imageName"];

[tempDic setObject:tempArr forKey:@"newCat"];

NSUserDefaults *myDefaults = [NSUserDefaults standardUserDefaults];

[myDefaults setObject:tempDic forKey:@"myKey"];

NSLog(@"%@",[myDefaults objectForKey:@"myKey"]);

In the console it prints:在控制台中打印:

{
newCat =     (
    CategoryName,
    imageName
);
}

Update as per comment:根据评论更新:

You should use Different key to store different objects like, newCat, newCat1, newCat2 etc or you can use mutablearray instead of dictionary and can add multiple object and retrieve it by it's index.您应该使用不同的键来存储不同的对象,如newCat, newCat1, newCat2等,或者您可以使用mutablearray而不是字典,并且可以添加多个对象并通过它的索引检索它。

Swift version:斯威夫特版本:

Save an array of Dictionary in UserDefaults在 UserDefaults 中保存一个 Dictionary 数组

func save(arr: NSArray) {
    guard let data = try? NSKeyedArchiver.archivedData(withRootObject: arr , requiringSecureCoding: false) as Data
    else { fatalError("Can't encode data") }
    UserDefaults.standard.set(data, forKey: "ReferredBy")
}

Get an array of Dictionary from UserDefaults从 UserDefaults 获取字典数组

func get() -> NSArray {

    if let unarchivedObject = UserDefaults.standard.object(forKey: "ReferredBy") as? Data {
        guard let nsArray = try? NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(unarchivedObject) as! NSArray else {
            return NSArray()
        }
        return nsArray            
    }
    return NSArray()
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM