How to use BOOL and String - iphone

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;

Related

how to print out bool in objective c

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

Pass an NSString variable to a function and modify it

I'm new in objective-c, this is my first post. This is my problem:
In my main file I have a variable: NSString *var;
Then I have a function:
-(BOOL) myfunction:(NSString *)myvar {
myvar = #"OK!";
return YES;
}
Now in the main file I do:
NSString *var;
BOOL control = myfunction:var;
if(control)
NSLog(#"var is: %#",var);
but the output is "var is: ". If I built in debug mode, and put a breakpoint at the start of function myfunction the memory address of myvar is equal to var, but after the assignment the address of myvar is different from the address of var. How can I solve it? thanks in advance!
While the answers given so far are correct. I think a more pertinent question is why you would want to do this.
It looks you want to have a defensive programming style where the return code indicates success or failure.
A more Objective-C like way to do this would be to pass the string and an NSError ** as a parameter and return the string or a nil to indicate failure as described in the Error Handling Programming Guide
So the way to write this would be:
- (NSString *)aStringWithError:(NSError **)outError {
returnString = #"OK";
if (!returnString) {
if (outError != NULL) {
NSString *myErrorDomain = #"com.company.app.errors";
NSInteger errNo = 1;
*outError = [[[NSError alloc] initWithDomain:myErrorDomain code:errNo userInfo:nil] autorelease];
}
}
return returnString;
}
And to use it:
NSError *error;
NSString *stringVariable = [self aStringWithError:&error];
if (!stringVariable) {
// The function failed, so it returned nil and the error details are in the error variable
NSLog(#"Call failed with error: %ld", [error code]);
}
This is a trivial example, but you can see that you can construct and return far more meaningful information about the error rather than just whether it succeeded or not.
You can also use NSMutableString.
-(BOOL) myfunction:(NSMutableString *)myvar {
[myvar setString:#"OK!"];
return YES;
}
and change your call site as follows:
NSMutableString *var = [NSMutableString string];
BOOL control = [self myfunction:var];
if(control)
NSLog(#"var is: %#",var);
Syntactically you need to fix your myFunction invocation like so:
BOOL control = [self myfunction:var];
The real problem here is that inside of myFunction you are assigning a string value to a local string variable only, whereas you want to change the underlying string that it points to. This is usually the wrong approach in Obj-C, but you can do it like so:
-(BOOL)myfunction:(NSString **)myvar
{
*myvar = #"OK!";
return YES;
}
NSString *var;
BOOL control = [self myfunction:&var];
if(control)
NSLog(#"var is: %#",var);

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 convert and compare NSNumber to BOOL?

First I convert BOOL value to NSNumber in order to put it into NSUserDefaults. Later I would like to retrieve the BOOL value from the NSUserDefaults, but obviously I get NSNumber instead of BOOL. My questions are?
how to convert back from NSNumber to BOOL?
How to compare NSNumber to BOOL value.
Currently I have:
if (someNSNumberValue == [NSNumber numberWithBool:NO]) {
do something
}
any better way to to the comparison?
Thanks!
You currently compare two pointers. Use NSNumbers methods instead to actually compare the two:
if([someNSNumberValue isEqualToNumber:[NSNumber numberWithBool:NO]]) {
// ...
}
To get the bool value from a NSNumber use -(BOOL)boolValue:
BOOL b = [num boolValue];
With that the comparison would be easier to read for me this way:
if([num boolValue] == NO) {
// ...
}
Swift 4:
let newBoolValue = nsNumberValue.boolValue
NSUserDefaults has two methods to transparently operate with booleans:
- (BOOL)boolForKey:(NSString *)defaultName
- (void)setBool:(BOOL)value forKey:(NSString *)defaultName
The ONLY way I managed to finagle a NSNumber's "booleanity" from its NSConcreteValue(doh!) was with the following...
id x = [self valueForKey:#"aBoolMaybe"];
if ([x respondsToSelector:#selector(boolValue)] &&
[x isKindOfClass:objc_getClass("__NSCFNumber")])
[self doSomethingThatExpectsABool:[x boolValue]];
Every other trick... FAILED. Buyer beware, this isn't foolproof (__NSCFNumber may well be platform/machine specific - it is solely Apple's implementation detail)... but as they say.. nothing else worked!

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];