问题描述
NSUserDefaults有 integerForKey:
, setInteger:forKey:
和 stringForKey:
,但没有 setString:forKey:
。
NSUserDefaults has integerForKey:
, setInteger:forKey:
and stringForKey:
, but does not have setString:forKey:
.
如何将字符串设置为NSUserDefaults ?它有 setObject:forKey:
但是,在Swift中,String是一个结构。是否可以使用 setObject:forKey:
来存储字符串?
How do you set a string to NSUserDefaults? It has setObject:forKey:
but, in Swift, String is a struct. Is it ok to use setObject:forKey:
to store a string?
推荐答案
可用于应用在参考讨论中找到的字符串:
The reason that setObject can be used to apply a string is found in the discussion of the reference:
由于Swift String桥接到NSString,因此使用setObject有效。但是,由于使用setObject setter在NSUserDefaults中不接受所提到的其他类型;他们有自己的便利设置者。
Since Swift String is bridged to NSString, the usage of setObject is valid. However as the other types mentioned are not accepted in NSUserDefaults using the setObject setter; they have their own convenience setters.
尽管如此,几乎所有可以想到的东西都可以被序列化并使用带有NSData参数的setObject放入NSUserDefaults(如SO所示)。
Notwithstanding this, almost anything one can think of can be serialized and placed into NSUserDefaults using setObject with an NSData argument (as noted elsewhere on SO).
这篇关于Swift NSUserDefaults setString:forKey:?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!