0

I'm not getting the Boolean type?

Here is my code, what i m doing wrong?

id val = [ dict objectForKey:key ];

if ([ val isKindOfClass:[ NSString class ] ] )
   print "string";
else if( [ val  isKindOfClass:[ NSNumber class ] ] )
   print "number";
else if( [ val  isKindOfClass:[ BOOL class ] ] )
   print "bool";

Not getting the boolean type.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
  • You cant store BOOL in an NSDictionary. See docs. (When you parse a JSON, booleans will be stored as NSIntegers 0 and 1.) – ilmiacs Oct 20 '12 at 10:54
  • Besides, your print statements are bad. – ilmiacs Oct 20 '12 at 10:55
  • As You're new to [stackoverflow](http://stackoverflow.com/) also read the [FAQ](http://stackoverflow.com/faq). When you found a correct answer you have to accept it and up vote. – TheTiger Oct 20 '12 at 11:07
  • @ilmiacs NSIntegers dont work, wither ;) they are stored as `[NSNumber nuberWithBOOL:]` – Ahti Oct 20 '12 at 11:29
  • Check this answer: http://stackoverflow.com/questions/2518761/get-type-of-nsnumber You can create a NSNumbers and then check its objCType. – atxe Oct 20 '12 at 11:42
  • @Ahti Yes sorry, that's what I meant. – ilmiacs Oct 20 '12 at 12:24

2 Answers2

1

You cant save BOOL value in NSDictionary directly because it is not an object. So first you will have to change it in NSNumber then save it in NSDictionary and then compare isKindOfClass:[NSNumber Class] instead of comparing the [BOOL class].

Example:-

BOOL value = YES;
NSDictionary *dict = [[NSDictionary alloc]initWithObjectsAndKeys:[NSNumber numberWithBool:value],@"Bool", nil];

id val = [dict valueForKey:@"Bool"];
if([val isKindOfClass:[NSNumber class]])
{
    //NSNumber Class
}

EDIT:

You cant cast a BOOL value into NSString directly. If you want BOOL value in NSString format you will have to make your own methods. Here is a small example of this using macro.

Define this macro in which class you want to cast a BOOL value to NSString.

#define NSStringFromBOOL(aBOOL) aBOOL? @"YES" : @"NO"

Then simply call this -

NSString *bool_string = NSStringFromBOOL(YES);
NSLog(@"%@",bool_string);

It will print YES instead of '1'.

TheTiger
  • 13,264
  • 3
  • 57
  • 82
  • hey i want to set boolean value as Yes/No format not in the 0 and 1, I have string , number , and bool value so how can i do it. – user1761344 Oct 20 '12 at 11:39
0

BOOL is not a class nor an Objective-C object type. It's a scalar, typedeffed from a C primitive type (signed char). You can't use it like this.