简体   繁体   English

我如何使用NSData将布尔值保存并检索到文件中

[英]How would I save and retrieve a boolean into a file using NSData

I want to save a boolean into a file and also I want to know how you would retrieve it again. 我想将布尔值保存到文件中,也想知道如何再次检索它。 I mainly want to use this for when the iPhone terminates and finishes launching in their respected methods. 我主要想在iPhone终止并以其受尊敬的方法完成启动时使用它。

An alternative to manually saving to a file is to use NSUserDefaults. 手动保存到文件的另一种方法是使用NSUserDefaults。

To save: 保存:

[[NSUserDefaults standardUserDefaults] setBool:myBool forKey:@"myBool"];

To load: 装载:

myBool = [[NSUserDefaults standardUserDefaults] boolForKey:@"myBool"];

You can convert a boolean to an NSNumber using the convenience constructor (class method) numberWithBool: . 您可以使用便捷构造函数(类方法) numberWithBool:将布尔值转换为NSNumber。

NSNumber can be persisted by adding it to an NSDictionary and using writeToFile:atomically: to save the dictionary as a property list (plist). 可以通过将NSNumber添加到NSDictionary并使用writeToFile:atomically:将字典保存为属性列表(plist)来持久化。

NSNumber objects are also used to represent and persist booleans (as well as integers and floats, but not currency) in Core Data. NSNumber对象还用于表示和保留Core Data中的布尔值(以及整数和浮点数,但不包括货币)。

您可以将其保存为整数(1/0 = true / false)吗?

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

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