Xcode - build string from multiple sources - objective-c

Hi just starting to learn this language, more of a javascript/PHP guy...
I can't seem to figure out the proper syntax and after searching the internets for a straight answer or explanation I decided to bother you SOF community:
This works as I want it to work:
self.displaysTheStack.text = [self.displaysTheStack.text stringByAppendingString:#" "];
self.displaysTheStack.text = [self.displaysTheStack.text stringByAppendingString:operation];
self.displaysTheStack.text = [self.displaysTheStack.text stringByAppendingString:#" "];
I wanted to know if I could do the same thing in less lines something like:
NSString *displayTheArrayText = [NSString stringWithFormat:#" ",operation,#" "];
self.displaysTheStack.text = [self.displaysTheStack.text stringByAppendingString:displayTheArrayText];
When I do it this way I get the Two #" " (spaces) but "operation" doesn't show up: why and how do I write the latter command properly?

stringWithFormat: uses C-style formats similar to those used by printf
you probably want something like that:
NSString *displayTheArrayText = [NSString stringWithFormat:#" %# ",operation];
have a look at Formatting String Objects

self.displaysTheStack.text = [NSString stringWithFormat:#"%# %# ", self.displaysTheStack.text, operation];
Alternately:
NSMutableString *string = [NSMutableString stringWithString:self.displaysTheStack.text];
[string appendFormat:#" %# ", operation];
self.displaysTheStack.text = string;

Related

Dynamically change number of variables in NSStringWithFormat

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 ?: #""];

How to leave a set number of spaces in NSString?

I have separate text objects for the unchanging portion (i.e. "Bonus Score: (+7%)") and the changing portion (e.g. "247,890"). Since they're separate, I want to leave space in the unchanging portion to display the number.
What I first tried was:
NSString* numberString = #"247,890";
NSString* blankScore = [#"" stringByPaddingToLength:[numberString length] withString: #" " startingAtIndex:0];
NSString* baseDisplay = [NSString stringWithFormat:#"BONUS SCORE: %# (+7%%)", blankScore];
'blankScore' was the correct length, but the resulting baseDisplay seemed to trim the spaces around where blankScore would be, making it too small of a space for the displayed number.
Next I tried another way of creating blankScore:
NSString* blankScore = [numberString stringByReplacingCharactersInRange:NSMakeRange(0, [numberString length]) withString:#" "];
But this returned a blankScore of length 1.
Am I understanding these NSString methods incorrectly? I checked the docs, and it seems like my understanding of these methods aligns with what's written there, but I still don't understand why I can't get my baseDisplay to have the correct number of spaces.
Have you printed blankScore on the console using NSLog? Actually your string is correct, but the output is trimmed at end of lines - this is why you see it as described.
#H2CO3 is on to the right solution. You should be using:
NSString *baseDisplay = [NSString stringWithFormat:#"BONUS SCORE: %# (+7%%)", numberString];
To make this work even better, you may want to consider an NSNumberFormatter to correctly format the changing part before inserting it into the baseDisplay object. Something like this:
NSNumber *changingNumber = [NSNumber numberWithDouble:247890];
NSNumberFormatter *correctFormat = [[NSNumberFormatter alloc] init];
[correctFormat setNumberStyle:NSNumberFormatterDecimalStyle];
[correctFormat setHasThousandSeparators:YES];
[correctFormat setUsesGroupingSeparator:YES];
NSString *numberString = [correctFormat stringFromNumber:changingNumber];
NSString *baseDisplay = [NSString stringWithFormat:#"BONUS SCORE: %# (+7%%)", numberString];
This way no matter what number you throw at it, it will correctly display "1,234,456" or "34,567", whatever.
EDIT:
Based on the comments to my answer you will need to use:
stringByPaddingToLength:withString:startingAtIndex:
It should look something like this:
NSString *templateString = #"BONUS SCORE:";
NSString *templateString2 = #"(+7%%)";
NSUInteger baseStringLength = [templateString length] + [numberString length];
NSString *spacedString = [templateString stringByPaddingToLength:baseStringLength withString:#" " startingAtIndex:0];
NSString *baseDisplay = [NSString stringWithFormat:#"%#%#", spacedString, templateString2];

Adding ":" between two words in stringByAppendingString

I need to add : between 2 strings when i add them together.
I couldnt find simple way to do that,and i am sure there is .
NSString *inBase64;
inBase64=[userName.text stringByAppendingString:idNumber.text];
I need: userName:idNumber
Thnks
You can use stringWithFormat...
NSString *inBase64 = [NSString stringWithFormat:#"%#:%#", userName.text, idNumber.text];
Another way. Useful when you have a lot of string parts:
NSArray *parts = #[ userName.text, idNumber.text, /* more */ ];
NSString *string = [parts componentsJoinedByString:#":"];
instead of stringByAppendingString: use stringByAppendingFormat:, like this:
inBase64 = [userName.text stringByAppendingFormat:#":%#", idNumber.text];
you can also use the [NSString stringWithFormat:] method, like this:
inBase64 = [NSString stringWithFormat:#"%#:%#", userName.text, idNumber.text];

Help with HelloWorld Objective-C

I'm Very new to Objective-C iPhone programming. I'm kinda gonna go with the trial-and-error method on this one:P. So my question has to do with getting a name. Here's my code:
-(IBAction)sayHello:(id)sender{
NSString *name = [textField text];
label.text = [NSString stringWithFormat:#"Hello ", name];
What this does is get the text from a UITextField (I already have this setup) and outputs to a UILabel. I would think this would work, but apparently not, because it just outputs "Hello ". Missing the name. Help would be appreciated :)
Thanks,
Eric
EDIT: Thanks to all that responded. It worked! :)
It should read:
label.text = [NSString stringWithFormat:#"Hello %#", name];
stringWithFormat uses "%" sequences to insert values into the string it's building. You use different "%" sequences depending on what type of value you're inserting: "%#" is for Objective-C objects, "%d" is for integers, and so forth. You can insert multiple values by using multiple "%" sequences, for example:
label.text = [NSString stringWithFormat:#"Hello %# %# and your %d friends", firstName, lastName, 7];
Try this:
[NSString stringWithFormat:#"Hello %#", name];
-(IBAction)sayHello:(id)sender{
NSString *name = [textField text];
label.text = [NSString stringWithFormat:#"Hello %#", name];
}
You have to add %#, so that it will place your name string in the formatted string.
You need a format specifier:
label.text = [NSString stringWithFormat:#"Hello %#", name];
The %# format specifier means "an NSObject reference". For formatting other datatypes - int, double, etc. you should use %d, %f and so on.

Merge 5 NSStrings in Objective-C

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.