cloudVision
cloudVision

Reputation: 279

How to Convert an array values into booleans values

I have an array like this

myArray=[0,0,1];

I want to convert this array values into boolean values like below

myArray=[false,false,true];

I assign array values into strings

mystring=[myarray objectAtIndex:0];

if possible here also i can convert the 0, 1s into boolean values.

Upvotes: 0

Views: 243

Answers (2)

Amin Negm-Awad
Amin Negm-Awad

Reputation: 16650

The short answer is in the code below:

// Do nothing

The long answer is like this:

You do not have an array as you described. The correct code would be:

myArray=@[ @0, @0, @1]; // NSArray instance of NSNumber instances.

You do not want to have an array as you described. The correct code would be:

myArray=@[ @NO, @NO, @YES]; // NSArray instance of NSNumber instances.

Since both NSNumber instances containing integer values or boolean values are the same, [@0 boolValue] will return NO and [@1 boolValue] will return YES. So you already have, what you want to get.

Your real problem is the translation of values (integer or boolean, while boolean values are integer values) into a string. You can use a number formatter for this or simply a conditional expression:

BOOL b = [myarray[0] boolValue];
mystring = b?@"true":@"false";

Upvotes: 0

Lucas Huang
Lucas Huang

Reputation: 4016

You can keep the way you store the value. Whatever number you store bigger than one, it will be considered as YES when you retrieve as BOOL type. However, it will give you the actual number if you retrieve it as NSInteger or int. So, use booleanValue method to retrieve like so:

NSNumber *value1 = myArray[0];
BOOL boolValue1 = [value1 booleanValue];

Upvotes: 1

Related Questions