简体   繁体   English

从用户默认值获取值并创建NSMutableDictionary

[英]Getting values from userdefaults and creating an NSMutableDictionary

I am trying to create a dictionary which is a replica for NSUserdefaults. 我正在尝试创建一个字典,该字典是NSUserdefaults的副本。 I want the dictionary to contain same values and keys. 我希望字典包含相同的值和键。 But, we need to convert bool and int values to NSNumber when we save it to dictionary. 但是,将bool和int值保存到字典时,需要将其转换为NSNumber。 Right now i am doing the following. 现在我正在做以下事情。 But not sure which value is bool value and int value. 但是不确定哪个值是布尔值和整数值。 If I can get to know the type of the value I can do rest. 如果我可以知道值的类型,就可以休息了。 Is there any way to check the value whether it is bool or int. 有什么方法可以检查值是bool还是int。

NSArray *availableUserDefaultsKeys = [NSArray arrayWithObjects:@"Key1", @"Key2",nil];
NSMutableDictionary *userDefaultsDictionary = [NSMutableDictionary dictionary];
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];

for (NSString *key in availableUserDefaultsKeys) {
    id value = [userDefaults objectForKey:key];
    if (value != nil) { // Is there any way to check whether the value is bool or int here
        [userDefaultsDictionary setObject:value forKey:key];
    } else {
        [userDefaultsDictionary setObject:[NSNull null] forKey:key];
    }
}

I have checked the debug.plist which has all the user defaults stored, In that we have type field where it specifies the type. 我已经检查了debug.plist,其中存储了所有用户默认值,其中我们在type字段中指定了类型。 Can we get the type from this field. 我们可以从该字段中获取类型吗?

请检查屏幕截图中的文件类型

You can use this way: 您可以使用这种方式:

// v is NSNumber
if ((strcmp([v objCType], @encode(BOOL) == 0) {
    // this is BOOL
}

And there are @encode(int) @encode(float) 还有@encode(int)@encode(float)

You should avoid directly saving seperated data to NSUserDefaults, you can pack them in an object, and this object should conform NSCoding protocol. 您应该避免将单独的数据直接保存到NSUserDefaults中,可以将它们打包在一个对象中,并且该对象应符合NSCoding协议。 Then after you read the data out, you will know the exact type. 然后,在读取数据之后,您将知道确切的类型。

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

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