I have got a problem with converting an NSNumber value to an NSString
MyPowerOnOrNot is an NSNumber witch can only return a 1 or 0
and myString is an NSString..
myString = [NSString stringWithFormat:@"%d", [myPowerOnOrNot stringValue]];
NSLog(@"%@",myString);
if(myString == @"1") {
[tablearrayPOWERSTATUS addObject:[NSString stringWithFormat:@"%@",@"ON"]];
}
else if(myString == @"0") {
[tablearrayPOWERSTATUS addObject:[NSString stringWithFormat:@"%@",@"OFF"]];
}
What is wrong with this?
The NSLog shows 0 or 1 in the console as a string but I can’t check it if it is 1 or 0 in an if statement?
If doesn’t jump into the statements when it actually should.. I really don’t understand why this doesn’t works..
Any help would be very nice!
A couple of problems
-stringValue sent to an
NSNumbergives you a reference to a string. The format specifier%dis for the Cinttype. What would happen in this case is that myString would contain the address of the NSString returned by[myPowerOnOrNot stringValue]. Or, on 64 bit, it would return half of that address. You could actually use[myPowerOnOrNot stringValue]directly and avoid the relatively expensive-stringWithFormat:myStringand@"1"are not necessarily the same object. Your condition only checks that the references are identical. In general with Objective-C you should use-isEqual:for equality of objects, but as we know these are strings, you can use-isEqualToString:Or even better, do a numeric comparison of your NSNumber converted to an int.
Finally if
myPowerOnOrNotis not supposed to have any value other than 0 or 1, consider having a catchallelsethat asserts or throws an exception just in casemyPowerOnOrNotaccidentally gets set wrong by a bug.