Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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?

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]];
like image 612
Christian Gossain Avatar asked Dec 02 '10 20:12

Christian Gossain


People also ask

Can NSArray contain nil?

arrays can't contain nil. There is a special object, NSNull ( [NSNull null] ), that serves as a placeholder for nil.

How do you declare NSArray in Objective-C?

Creating NSArray Objects Using Array Literals In addition to the provided initializers, such as initWithObjects: , you can create an NSArray object using an array literal. In Objective-C, the compiler generates code that makes an underlying call to the init(objects:count:) method.

Is NSArray ordered?

The workhorse of collection types is the array. In Objective-C, arrays take the form of the NSArray class. An NSArray represents an ordered collection of objects. This distinction of being an ordered collection is what makes NSArray the go-to class that it is.

What is NSMutableArray?

The NSMutableArray class declares the programmatic interface to objects that manage a modifiable array of objects. This class adds insertion and deletion operations to the basic array-handling behavior inherited from NSArray . NSMutableArray is “toll-free bridged” with its Core Foundation counterpart, CFMutableArray .


1 Answers

Since NSArray only takes in (id)s (i.e. Objective-C pointers to objects), you can only store objects.

The common way to store a BOOL value in an object is with the NSNumber class:

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

To access it, grab that NSNumber object and send it a boolValue message:

[mySwitch setOn:[[array objectAtIndex:0] boolValue]];
like image 128
BoltClock Avatar answered Sep 16 '22 22:09

BoltClock