在Objective-C和Swift之间的UserDefaults [英] UserDefaults between Objective-C and Swift

查看:189
本文介绍了在Objective-C和Swift之间的UserDefaults的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只是在这里要格外小心...

Just trying to be extra careful here...

如果我有一个在UserDefaults中保存了一个值的应用程序,例如在Objective-C中:

If I have an app that saved a value in UserDefaults like this in Objective-C:

NSString *newString = textField.text;
[[NSUserDefaults standardUserDefaults] setObject: newString forKey:@"textKey"];

当我发布对现在已在Swift中编码的应用程序的更新时,这是否是检查此值是否存在的正确方法:

Would this be the proper way of checking whether this value exists when I release an update to the app that is now coded in Swift:

if (UserDefaults.standard.object(forKey: "textKey") as? String) != nil {
     print("There is a string")
} else {
     print("No string exists") 
}

由于已引入.string(forKey :)和.bool(forKey :),因此我尝试使用它们,但是最安全的方法是将其保存为对象,然后将其拉出为对象,然后进行测试是?字符串"?

I try to use .string(forKey:) and .bool(forKey:) since they've been introduced, but is it safest since this was saved as an object to pull it out as an object and then test it with "as? String"?

同一问题的棘手版本:

NSDictionary对象的NSMutableArray被保存为UserDefaults中的对象

An NSMutableArray of NSDictionary objects was saved as an object in UserDefaults

if let oldData = UserDefaults.standard.object(forKey: "theData") as? [NSMutableDictionary] {

}

NSDictionary和NSMutableDictionary在这里可以互换吗?

Will NSDictionary and NSMutableDictionary be interchangeable here?

谢谢!

推荐答案

[NS]UserDefaults由plist和字典支持. Objective-C字符串作为<string>Some Text</string>保存到plist.

[NS]UserDefaults is backed by a plist and a dictionary. The Objective-C string was saved to the plist as a <string>Some Text</string>.

在Swift中加载的同一个plist为该键提供了一个字符串.

That same plist loaded in Swift gives a string for that key.

因此,使用UserDefaults.string读取用Objective-C存储的值应该没有问题.当然,您仍然需要验证该值是否确实存在.

So you should have no issue using UserDefaults.string to read the value stored with Objective-C. Of course you still need to verify the value actually exists.

if let str = UserDefaults.standard.string(forKey: "textKey") {
    print("Found \(str)")
} else {
    print("No string for key")
}

即使原始值不是字符串,使用UserDefault.string也是安全的.它只会为非字符串值返回nil.

Even if the original value isn't a string, using UserDefault.string is safe. It will simply return nil for non-string values.

关于NSDictionaryNSMutableDictionary,请注意UserDefaults仅检索不可变的NSDictionary.您无法从UserDefaults读取NSMutableDictionary(或数组).

With regard to NSDictionary and NSMutableDictionary, note that UserDefaults only retrieves immutable NSDictionary. You can't read an NSMutableDictionary (or array) from UserDefaults.

请注意,您可以安全地使用Swift字典来阅读原始的NSDictionary.无需使用Objective-C类.

Note you can safely use a Swift dictionary to read the original NSDictionary. No need to use Objective-C classes.

这篇关于在Objective-C和Swift之间的UserDefaults的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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