I am trying to convert from an int to a string but I am having trouble. I followed the execution through the debugger and the string 'myT' gets the value of 'sum' but the 'if' statement does not work correctly if the 'sum' is 10,11,12. Should I not be using a primitive int type to store the number? Also, both methods I tried (see commented-out code) fail to follow the true path of the 'if' statement. Thanks!
int x = [my1 intValue];
int y = [my2 intValue];
int sum = x+y;
//myT = [NSString stringWithFormat:@"%d", sum];
myT = [[NSNumber numberWithInt:sum] stringValue];
if(myT==@"10" || myT==@"11" || myT==@"12")
action = @"numGreaterThanNine";
This question is related to
objective-c
nsstring
int
int val1 = [textBox1.text integerValue];
int val2 = [textBox2.text integerValue];
int resultValue = val1 * val2;
textBox3.text = [NSString stringWithFormat: @"%d", resultValue];
If you just need an int to a string as you suggest, I've found the easiest way is to do as below:
[NSString stringWithFormat:@"%d",numberYouAreTryingToConvert]
Simply convert int
to NSString
use :
int x=10;
NSString *strX=[NSString stringWithFormat:@"%d",x];
==
shouldn't be used to compare objects in your if
. For NSString
use isEqualToString:
to compare them.
You can use literals, it's more compact.
NSString* myString = [@(17) stringValue];
(Boxes as a NSNumber and uses its stringValue method)
Dot grammar maybe more swift!
@(intValueDemo).stringValue
for example
int intValueDemo = 1;
//or
NSInteger intValueDemo = 1;
//So you can use dot grammar
NSLog(@"%@",@(intValueDemo).stringValue);
Source: Stackoverflow.com