简体   繁体   English

如何将布尔值存储到NSArray?

[英]How to store a boolean value to an NSArray?

So I'm storing user settings in a plist file and to do that I'm adding data to an NSArray. 所以我将用户设置存储在plist文件中,为此我将数据添加到NSArray中。 This approach is working for me. 这种方法对我有用。

My problem is that now I'm adding a UISwitch to the settings and I was wondering how to store their ON/OFF state to the array so that I can access that state at a later time? 我的问题是,现在我在设置中添加了一个UISwitch,我想知道如何将它们的ON / OFF状态存储到数组中,以便我以后可以访问该状态?

I'm adding data to the array like this: 我正在向数组添加数据,如下所示:

[array addObject: mySwitch.on];

Then I'm trying to set the state like this: 然后我试图设置这样的状态:

[mySwitch setOn:[array objectAtIndex:0]];

Since NSArray only takes in (id) s (ie Objective-C pointers to objects), you can only store objects. 由于NSArray只接受(id) s(即Objective-C指向对象),因此只能存储对象。

The common way to store a BOOL value in an object is with the NSNumber class: 在对象中存储BOOL值的常用方法是使用NSNumber类:

[array addObject:[NSNumber numberWithBool:mySwitch.on]];

To access it, grab that NSNumber object and send it a boolValue message: 要访问它,请获取该NSNumber对象并向其发送boolValue消息:

[mySwitch setOn:[[array objectAtIndex:0] boolValue]];

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

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