Is there any simple way how to initialize String in Objective-C with int such as in Java:
String myStr = 42 + "";
or I have to do
[NSString stringWithFormat:#"%d", 42];
everytime?
You could also use the NSNumber class for that:
NSNumber *number = [[NSNumber alloc] initWithInteger: val];
NSString *string = [number stringValue];
Perhaps not shorter, but it could be eventually faster.
Also you could create as said a helper method, than you wouldn't have to use more code than with the stringWithFormat: method.
Yes you have to do
[NSString stringWithFormat:#"%d", 42];
for Integer to string conversion.
Using a constant, like 42 in your example, you can write
NSString *myString = #"42";
Using a variable or expression, you can write
[NSString stringWithFormat:#"%d", myValue];
Related
Let's say I have string like this:
NSString *myString = [NSString stringWithFormat:#"%#%#%#%#%#",variable1,variable2,variable3,variable4,variable5];
and if variable2 is nil I don't want that in my string, like this:
NSString *myString = [NSString stringWithFormat:#"%#%#%#%#",variable1,variable3,variable4,variable5];
Question
Is there any way to do this without having a lot of if-statements?
Don't use [NSString stringWithFormat:], and instead create an NSMutableString and append strings as necessary:
NSMutableString *s = [[NSMutableString alloc] init];
if (variable1)
[s appendString:variable1];
if (variable2)
[s appendString:variable2];
if (variable3)
[s appendString:variable3];
if (variable4)
[s appendString:variable4];
if (variable5)
[s appendString:variable5];
(sorry I missed your point about "not having lots of if statements", however I don't think it can be avoided).
The easiest way is to use the compacted ternary operator to replace a null with an empty string. Using a slightly abridged version of your example:
NSString *myString = [NSString stringWithFormat:#"%#%#",variable1 ?: #"",variable2 ?: #""];
I need to convert two numbers to string in Objective-C.
One is a long number and the other is a float.
I searched on the internet for a solution and everyone uses stringWithFormat: but I can't make it work.
I try
NSString *myString = [NSString stringWithFormat: #"%f", floatValue]
for 12345678.1234 and get "12345678.00000" as output
and
NSString *myString = [NSString stringWithFormat: #"%d", longValue]
Can somebody show me how to use stringWithFormat: correctly?
This article discusses how to use various formatting strings to convert numbers/objects into NSString instances:
String Programming Guide: Formatting String Objects
Which use the formats specified here:
String Programming Guide: String Format Specifiers
For your float, you'd want:
[NSString stringWithFormat:#"%1.6f", floatValue]
And for your long:
[NSString stringWithFormat:#"%ld", longValue] // Use %lu for unsigned longs
But honestly, it's sometimes easier to just use the NSNumber class:
[[NSNumber numberWithFloat:floatValue] stringValue];
[[NSNumber numberWithLong:longValue] stringValue];
floatValue has to be a double. At least this compiles correctly and does what is expected on my machine
Floats can only store about 8 decimal digits and your number 12345678.1234 requires more precision than that, hence only about the 8 most significant digit are stored in a float.
double floatValue = 12345678.1234;
NSString *myString = [NSString stringWithFormat: #"%f", floatValue];
results in
2011-11-04 11:40:26.295 Test basic command line[7886:130b] floatValue = 12345678.123400
You should use NSNumberFormatter eg:
NSNumberFormatter * nFormatter = [[NSNumberFormatter alloc] init];
[nFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber *num = [nFormatter numberFromString:#"12345678.1234"];
[nFormatter release];
I'm busy working on an iPad application and my web service returns pretty simple JSON data. All seems well and I have other methods doing this same conversion without issue however, I have 1 method that returns a random string when doing a integer -> string conversion.
My userdata object below is a NSDictionary created by the SBJSON parser. The value when debugging of [userdata objectForKey:#"UserID"] is 1.
However when I do this
NSString *userId = [NSString stringWithFormat:#"%d", [userdata objectForKey:#"UserID"]];
The value in userId is or appears to be a random number such as 23425234. I also tried the %d in my format but got the same result.
Because it is an object, not an int, you see the address of the object, instead, you can do that:
NSString *userId = [NSString stringWithFormat:#"%#", [userdata objectForKey:#"UserID"]];
^
Try with:
NSString *userId = [NSString stringWithFormat:#"%d", [[userdata objectForKey:#"UserID"] intValue]];
Or:
NSString *userId = [NSString stringWithFormat:#"%#", [userdata objectForKey:#"UserID"]];
object for key is probably NSNumber and not int...
When I have pf:/Abc/def/, how can I get the /Abc/def/?
With Python, I can use
string = 'pf:/Abc/def/'
string.split(':')[1]
or even
string[3:]
What's the equivalent function in Objective-C?
NSString *string = [NSString stringWithFormat:#"pf:/Abc/def/"];
NSArray *components = [string componentsSeparatedByString: #":"];
NSString *string2 = (NSString*) [components objectAtIndex:1];
Reference: http://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/occ/instm/NSString/componentsSeparatedByString:
componentsSeparatedByString will return an NSArray. You grab the object at a certain index, and type cast it to NSString when storing it into another variable.
I have multiple NSStrings and i wish to merge them into one other, here is my code so far...
NSString *newURL = [_parameters objectForKey:#"url"];
NSString *emailBody = #"Hey!<br>I just snipped my long url with My Cool App for iPhone in just a few seconds!<p><b>"+newURL+#"</b></p>";
If you know the number of your existing strings, you can just concat them:
NSString* longString = [firstString stringByAppendingString:secondString];
or:
NSString* longString = [NSString stringWithFormat:#"A string: %#, a float: %1.2f", #"string", 31415.9265];
If you have an arbitrary number of strings, you could put them in an NSArray and join them with:
NSArray* chunks = ... get an array, say by splitting it;
NSString* string = [chunks componentsJoinedByString: #" :-) "];
(Taken from http://borkware.com/quickies/one?topic=NSString)
Another good resource for string handling in Cocoa is: "String Programming Guide"
You can try
NSString *emailBody = [ NSString stringWithFormat: #"Hey!<br>I just snipped my long url with Snippety Snip for iPhone in just a few seconds, why not check it out?<p><b>%#</b></p>", newURL ];
Given that you've got multiple strings I recommend using an Array:
NSArray *array = [NSArray arrayWithObjects:#"URL", #"person", "body"];
NSString *combined = [array componentsJoinedByString:#""];
Formatting string has better readability and less error-prone:
NSString *newURL = [_parameters objectForKey:#"url"];
NSString *emailBody = [NSString stringWithFormat:#"Hey!<br>I just snipped my long url with Snippety Snip for iPhone in just a few seconds, why not check it out?<p><b>%#</b></p>", newUrl, newUrl];
You can concatenate strings in Cocoa using:
[NSString stringByAppendingString:]
Or you could use the [NSString stringWithFormat] method which will allow you to specify a C-style format string with a variable argument list to populate the escape sequences.