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
myString = [NSString stringWithFormat:#"%d", [myPowerOnOrNot stringValue]];
-stringValue sent to an NSNumber gives you a reference to a string. The format specifier %d is for the C int type. 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:
if(myString == #"1")
myString and #"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:
if ([[myPowerOnOrNot stringValue] isEqualToString: #"1"])
Or even better, do a numeric comparison of your NSNumber converted to an int.
if ([myPowerOnOrNot intValue] == 1)
Finally if myPowerOnOrNot is not supposed to have any value other than 0 or 1, consider having a catchall else that asserts or throws an exception just in case myPowerOnOrNot accidentally gets set wrong by a bug.
"myString " is a reference to a string, not the value of the string itself.
The == operator will compare the reference to your string literal and so never return true.
Instead use
if( [myString isEqualToString:#"1"] )
This will compare the value of myString to "1"
In Objective C; you can't compare strings for equality using the == operator.
What you want to do here is as follows:
[tablearrayPOWERSTATUS addObject:([myPowerOnOrNot integerValue]?#"ON":#"OFF"])];
Compact, fast, delicious.
Related
So my problem is this:
I am receiving a JSON string from across the network. When decoded (using SBJSON libraries), it becomes an NSDictionary that SHOULD contain a number of some sort for the key 'userid'. I say 'should' because when I compare the value to an int, or an NSINTEGER, or NSNumber, it never evaluates correctly.
Here is the comparison in code:
NSDictionary *userDictionary = [userInfo objectAtIndex:indexPath.row];
if ([userDictionary objectForKey:#"userid"] == -1) {
//Do stuff
}
The value inside the dictionary I am testing with is -1. When I print it out to console using NSLog it even shows it is -1. Yet when I compare it to -1 in the 'if' statement, it evaluates to false when it should be true. I've even tried comparing to [NSNumber numberWithInt: -1], and it still evaluates to false.
What am I doing wrong? Thanks in advance for your help!
You are comparing a pointer to an object, not an integer itself. You must first convert the object into an integer:
if ([[userDictionary objectForKey:#"userid"] integerValue] == -1)
{
//Do stuff
}
Im wondering why this code won't work. It's for a calculator :)
I need the symbol (banana) to be recognised by the calculator and to use either +,- according to what the user inputs.
NSString *list = [Sum_TextField text];
NSArray *listItemsArray = [list componentsSeparatedByString:#" "];
int batman = [[listItemsArray objectAtIndex: 0] intValue];
NSString *banana = [listItemsArray objectAtIndex: 1];
int joker = [[listItemsArray objectAtIndex: 2] intValue];
{
Calculator* calc = [[Calculator alloc] init];
[calc setNum1:batman];
[calc setNum2:joker];
if ((banana = #"-"))
{
[calc minus];
}
else if ((banana = #"+"))
{
[calc add];
}
[Answer_TextField setText:[NSString stringWithFormat:#"%d", [calc answer]]];
}
}
To judge whether NSString is equal, you must use [#"AAAA" isEqualToString : #"BBBB"]. You can not use == , because they are not in the same address of the memory .
Here's how you want to do this:
if ([banana isEqualToString:#"-"])
{
[calc minus];
}
else if ([banana isEqualToString:#"+"])
{
[calc add];
}
= is assignment. It has absolutely nothing to do with comparison.
== is comparing the 2 expressions and see whether they are equal. This can be used to compare integral types (such as enum, char, int, short, long, long long, BOOL) or reference (check whether 2 pointers are pointing to the same object). Note that 2 pointers can point to 2 different object which contains the same value inside, but == will compare them as different. (Floating point type such as float and double requires a bit different method to compare equality).
As a method to preempt confusion between = and ==, for equality testing with ==, some people put the value on the left hand side, and the variable on the right hand side (e.g. 2 == variable). If they happen to mistype == to =, the compiler will complain.
If you want to compare the content of 2 objects, in this case is NSString, you should search for isEquals type of function. For NSString, you should use isEqualToString if you want to compare whether the 2 strings have the same content.
I am trying to implement the code below without success. Basically, I want to set the display name to use thisPhoto.userFullName if it is not 'Blank", else show thisPhoto.userName instead.
UILabel *thisUserNameLabel = (UILabel *)[cell.contentView viewWithTag:kUserNameValueTag];
NSLog(#"user full name %#",thisPhoto.userFullName);
NSLog(#"user name %#",thisPhoto.userName);
if (thisPhoto.userFullName && ![thisPhoto.userFullName isEqual:[NSNull null]] )
{
thisUserNameLabel.text = [NSString stringWithFormat:#"%#",thisPhoto.userFullName];
}
else if (thisPhoto.userFullName == #"")
{
thisUserNameLabel.text = [NSString stringWithFormat:#"%#",thisPhoto.userName];
}
Currently, even if userFullName is blank, my userName is still not displayed on the screen.
I'd prefer
if([thisPhoto.userFullName length])
Use -length. This will be 0 whenever the string is nil or the empty string #"". You generally want to treat both cases identically.
NSString *fullName = [thisPhoto userFullName];
thisUserNameLabel.text = [fullName length]? fullName : [thisPhoto userName];
I see a few points here
First - if your userFullName instance variable is NSString* then doing simple comparison with nil is enough:
if (thisPhoto.userFullName)
Unless, of course, you explicitly set it to be [NSNull null], which then requires the condition you wrote.
Second - comparing strings is done with isEqualToString: method so second condition should be rewritten as:
if ([thisPhoto.userFullName isEqualToString:#""]) {
...
}
Third - there's logic flaw - If your userFullName IS equal to empty string (#"") the code would still fall to the first branch. I.e. empty string (#"") is not equal to [NSNull null] or simple nil. Hence you should write to branches - one to handle empty string and nil, other one for normal value. So with a bit of refactoring your code becomes like this:
thisUserNameLabel.text = [NSString stringWithFormat:#"%#",thisPhoto.userFullName];
if (!thisPhoto.userFullName || [thisPhoto.userFullName isEqualToString:#""]) {
// do the empty string dance in case of empty userFullName.
}
If, as I suppose, thisPhoto.userFullName is a NSString you may try
[thisPhoto.userFullName isEqualToString:#""]
The other two answers are correct, and beat me to it. Rather than just repeat what they have said - I'll point out something else.
[NSNull null] is used to store nil values in collection classes (NSArray, NSSet, NSDictionary) that don't allow nil values to be stored in them.
So unless you're checking values that you get from a collection - there is no point checking against [NSNull null]
// this assumes userFullName and userName are strings and that userName is not nil
thisUserNameLabel.text = [thisPhoto.userFullName length] > 0 ? thisPhoto.userFullName : thisPhoto.userName;
"Blank" means #"", but also #" " or #"\n". So I would trim userFullName and check the length of that string.
if ([[thisPhoto.userFullName stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]] length] == 0) {
// it's blank!
}
I am trying to test to see if an NSString has the letters "PDF" as the first 3 letters:
if ([[[profiles stringForKey:#"response"] characterAtIndex:0] isEqualToString:#"P"]) {
//TODO
}
I started with this approach to see if I could at least narrow it down to those strings that start with "P" but I am getting an error on this that reads: "Invalid receiver type 'unichar'" AND "Cast to pointer from integer of different size"
Am I getting these errors because I am using the isEqualToString comparison? Does that attach the terminating zero to "P"? I tried to use the "==" comparison but I was also getting an error with that method.
if ([profiles hasPrefix:#"PDF"]) {
NSLog(#"my string starts with \"PDF\"");
}
You want to use the method substringToIndex instead of characterAtIndex. characterAtIndex is returning a unichar which is not an objective-c object to which isEqualToString can be sent.
Here is something that worked for me:
NSString* testString = #"PDFDocument";
NSString* subString = [testString substringToIndex:3];
if ( [subString isEqualToString:#"PDF"] == YES )
{
NSLog( #"same" );
}
I´m making a dictionary (this is my test app)
here is my code which not work:
- (IBAction) btnClickMe_Clicked:(id)sender {
NSString *kw = s.text;
NSString *encodedkw = [kw stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *mms = [NSString stringWithFormat: #"%#", encodedkw];
if (mms=NULL){
iMessageLabel.text=#"put text";
} else if (mms=#"a"){
iMessageLabel.text=#"this is a";
} else if (mms=#"b"){
iMessageLabel.text=#"this is b";
}
}
anybody have some idea with this ?
thanks
ALex
You cannot use == on NSString objects. Try doing this:
if (encodedkw == nil){
iMessageLabel.text=#"put text";
} else if ([encodedkw isEqualToString:#"a"]){
iMessageLabel.text=#"this is a";
} else if ([encodedkw isEqualToString:#"b"]){
iMessageLabel.text=#"this is b";
}
mms should be equal to encodedkw so I switched to using that. Also I'm using isEqualToString for string comparison. Finally, I've changed the null check to check against nil instead of NULL.
You've used = rather than ==
May it happen, that you need to call some kind of string manipulation routine like compare to compare strings, not just comparing the pointers?
Besides mms=NIL means assignment NIL to mms not comparison desired.
Upd.: NIL does not mean empty string. You should write [mms length] == 0 instead to see if the string is empty.