how to print out bool in objective c - iphone

I have set a bool value for key TCshow in my NSUserDefault,
I want to run a nslog test whether the key is saved or not, and i m trying to printout the bool value.
here is my code but it s not working, any suggestions?
- (IBAction)acceptAction:(id)sender {
//key store to nsuserdefault
self.storedKey = [[NSUserDefaults alloc] init];
[self.storedKey setBool:YES forKey:#"TCshow"];
//trying to print out yes or not, but not working...
NSLog(#"%#", [self.storedKey boolForKey:#"TCshow"]);
}

%# is for objects. BOOL is not an object. You should use %d.
It will print out 0 for FALSE/NO and 1 for TRUE/YES.

you should use
NSLog(flag ? #"Yes" : #"No");
here flag is your BOOL.

NSLog(#"The value is %s", [self.storedKey boolForKey:#"TCshow"] ? "TRUE" : "FALSE");

NSLog(#"%d", [self.storedKey boolForKey:#"TCshow"]);

if([self.storedKey boolForKey:#"TCshow"]){
NSLog(#"YES");
}
else{
NSLog(#"NO");
}
I think it will be helpful to you.

Just for the sake of using the new syntax you could always box the bool so that is an object and can be printed with %#
NSLog(#"%#", #( [self.storedKey boolForKey:#"TCshow"] ));

already answered in another post, copy to here:
Direct print bool to integer
BOOL curBool = FALSE;
NSLog(#"curBool=%d", curBool);
-> curBool=0
Convert bool to string
char* boolToStr(bool curBool){
return curBool ? "True": "False";
}
BOOL curBool = FALSE;
NSLog(#"curBool=%s", boolToStr(curBool));
-> curBool=False

Related

bool for key in NSMutableArray

I have a code like that
if ([dataArray valueForKey:#"success"]) {
[self.feedsArray addObjectsFromArray:dataArray];
NSLog(#"self.feedsArray: %#",self.feedsArray);
} else {
NSLog(#"no feed found ");
}
dataArray is a NSMutableArray which ultimately contains a JSON Dictionary.
but I am getting the same console output independent of success either TRUE or FALSE, but my console output is always same.my console output is:
for FALSE or NO:
self.feedsArray: (
{
action = register;
message = "Invalid parameters";
success = 0;
}
)
and for TRUE or YES:
self.feedsArray: (
{
action = register;
message = "valid parameters";
success = 1;
}
)
in both cases if part is executed.
in NSUserDefaults there is a method boolForKey but how to do this in case of NSMutableArray.
You need to read the fine print for [NSArray valueForKey:], specifically:
Returns an array containing the results of invoking valueForKey: using
key on each of the array's objects.
and:
The returned array contains NSNull elements for each object that
returns nil.
So if the array contains, say, 3 objects and none of them have a success key then you will get an array of 3 NSNull objects returned.
Therefore the if statement will fire whenever dataArray is non-empty, which is obviously not what you intended.
You should check the contents of the returned array:
BOOL succeeded = NO;
NSArray *results = [dataArray valueForKey:#"success"];
for (NSObject *obj in results) {
succeeded = [obj isKindOfClass:[NSNumber class]] && [(NSNumber *)obj boolValue];
if (succeeded)
break;
}
if (succeeded) {
[self.feedsArray addObjectsFromArray:dataArray];
NSLog(#"self.feedsArray: %#",self.feedsArray);
} else {
NSLog(#"no feed found ");
}
You can do this in simple way:
What i see in your response json value is, you have dictionary in dataArray at index 0
NSMutableDictionary *responseDict = [dataArray objectAtIndex:0];
if([[responseDict objectForKey:#"success"] boolValue])
{
NSLog(#"Success: 1");
}
{
NSLog(#"Success: 0");
}
Use index instead of key for an array.
NSDictionary dictionary = (NSDictionary *)dataArray[0];
if ([(NSNumber *)[dictionary objectForKey:#"success"] boolValue]) {
// ...
}
otherwise use if([[[dataArray objectAtIndex:0] valueForKey:#"success"] isEqualToString:#"1"])
An array does not store keys, the only way to access items in an array is by index.
You should be using an NSDictionary/NSMutableDictionary instead. If you want to use a bool store it as a NSNumber, [NSNumber numberWithBool:YES] and then use the instance method valueForBool to read it back.
Try this
if ([[dataArray valueForKey:#"success"]isEqualToString:#"1"]) {
[self.feedsArray addObjectsFromArray:dataArray];
NSLog(#"self.feedsArray: %#",self.feedsArray);
}
else {
NSLog(#"no feed found ");
}
It 'll work out.
use this if you want bool value
if([[dataArray valueForKey:#"success"] boolValue])
{
//i.e success is true
}
if response contains array of dictionaries then we can use loop and check condition,
here i is index variable of array,
if([[[dataArray objectAtIndex:i] objectForKey:#"success"] boolValue])
{
// success is true ,
}
Replace you code line
if ([dataArray valueForKey:#"success"]) {
}
with
if ([[dataArray valueForKey:#"success"] integerValue]) {
}
Hope it will work for you.
its working with replacing the line with
if ([[[dataArray objectAtIndex:0] valueForKey:#"success"] boolValue])

If statement doesn't work with downloaded data

I've written some code that posts data to a MySql database via PHP and the PHP code returns a value of either 'YES' or 'NO' via JSON. I then have an if statement that checks whether it is YES or NO. The if statement works perfectly when I set the 'worked' string manually, but not if I use the data from JSON. I have checked that it is set correctly using NSLog, and I really can't see what the problem could be. Here is a shortened version of my code:
-(void) dataDownloaded {
NSDictionary *theDictionary = [_theArray objectAtIndex:0];
NSString *worked = [theDictionary objectForKey:#"worked"];
NSLog(#"%#", worked);
if (worked == #"NO") {
//code for if it didn't work
} else if (worked == #"YES"){
//code for if it did work
} else {
//code for if it doesn't return either value
}
}
Thanks in advance to anyone who can work out what the problem is!
Your problem is you're using == to compare. That's not going to work. I think you need to read up on Objective-C - try http://www.cocoadevcentral.com/ for that. Here's how you should fix your code:
-(void) dataDownloaded {
NSDictionary *theDictionary = [_theArray objectAtIndex:0];
NSString *worked = [theDictionary objectForKey:#"worked"];
NSLog(#"%#", worked);
if ([worked isEqualToString:#"NO"]) {
//code for if it didn't work
} else if ([worked isEqualToString:#"YES"]){
//code for if it did work
} else {
//code for if it doesn't return either value
}
}
use isEqualToString: for string comparsions
if ([worked isEqualToString:#"NO"]) {
}

Boolean inside property list (Simple!)

I'm writing a small application right now and I got problems while reading out a property list...
My exact question is: How can I read out a boolean from the property list? Or better how can I read out this boolean from a NSDictionary?
Thanks, mavrick3.
The objects are stored as NSNumber objects, so to retrieve the BOOL you should use this method:
BOOL myBool = [someNSNumberObject boolValue];
To retrieve from a dictionary do something like this:
BOOl myBool = [[someDictionary objectForKey:#"someKey"] boolValue];
Documentation here: http://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSNumber_Class/Reference/Reference.html#//apple_ref/occ/instm/NSNumber/boolValue
Try storing the BOOL as a NSNumber ... then adding that to the Dictionary.
A simple example :
BOOL answered = YES;
NSNumber *answeredAsNumber = [NSNumber numberWithBool:answered];
[dict setObject:answeredAsNumber forKey:#"isAnswered"];
BOOL retrievedAnswered = [[dict objectForKey:#"isAnswered"] boolValue];
A BOOL should be stored as a NSNumber and you can access the BOOL value by saying
BOOL myvalue = [aNSNumber boolValue]

How to use BOOL and String

There is .plist file that has a key say XYZ and the value can be on or off.
Now I have this method BOOL isEnabled().
I want to check the value for that in that plist and return BOOL based on on or off.
How do I do that?
NSDictionary *plistDict = [NSDictionary dictionaryWithContentsOfFile:#"/var/mobile/Library/Preferences/com.apple.BTServer.airplane.plist"];
BOOL Location = [[plistDict objectForKey:#"airplaneMode"] boolValue];
return Location;
This code is for Location Toggle for iPhone/SBSettings. Here for Location toggle the values are stored as 1 and 0 but for Airplane mode for which I modifying this code the values are on/off.
How do I convert on /off to BOOL?
Is the on/off encoded as a string? If so, how about a string comparison?
NSString *strLocation = [[plistDict objectForKey:#"airplaneMode"] lowercaseString];
if ([strLocation isEqualToString:#"on"])
{
return TRUE;
}
return FALSE;
Yo probably want to use something like this to store a BOOL value on a dictionary/plist:
[myDictionary setObject:[NSNumber numberWithBool:YES]]
Though you'd use YES or NO depending on the value of the integer you want to store.
Or you can do a one-line if statement like so:
BOOL location = ([[plistDict objectForKey:#"airplaneMode"] isEqualToString:#"On"]) ? YES : NO;

What's wrong with this method?

I'm getting a warning: "Return makes pointer from integer without a cast" for this method...
+(BOOL *)getBoolFromString:(NSString *)boolStr
{
if(boolStr == #"true" || boolStr == #"1"){
return YES;
}
return NO;
}
BOOL is not a class or object, so returning a pointer to a BOOL is not the same as returning a BOOL.
You should remove the * in +(BOOL *) and everything will be ok.
Besides what #Jasarien and #jlehr have said, you have a problem with this:
(boolStr == #"true" || boolStr == #"1")
That's doing pointer comparison, not object equality. You want:
([boolStr isEqualToString:#"true"] || [boolStr isEqualToString:#"1"])
To get a BOOL from an NSString, all you need to do is send a -boolValue message, like so:
NSString *myString = #"true"; // or #"YES", etc.
BOOL bool = [myString boolValue];