How to append a char to NSNumber in Objective-C? - ios

I have a price parameter from my API price: 10
I want to show it in my textfield with appending "$" after it. But it doesn't show my number anyway even with casting it. Here is my code :
cell.price.text = [[NSString stringWithFormat:#"%i",
(NSNumber*)DIC[#"items"][indexPath.row][#"price"]] stringByAppendingString:#" $"];

to print an NSNumber you need to use %# instead of %i
cell.price.text = [NSString stringWithFormat:#"%# $",
(NSNumber*)DIC[#"items"][indexPath.row][#"price"]];

NSNumber is an object, do using the format %i will not work.
cell.price.text = [NSString stringWithFormat:#"%# $",
(NSNumber*)DIC[#"items"][indexPath.row][#"price"]];

Related

present NSString as a line of elements

I have an NSString that hold data (actually that could be presented an NSArray). and i want to output that on a label.
In NSLog my NSString output is:
(
"cristian_camino",
"daddu_02",
"_ukendt_babe_",
"imurtaza.zoeb"
)
What i want is, to present it like :"cristian_camino","daddu_02","_ukendt_babe_","imurtaza.zoeb"
In a single line.
I could accomplish that turning string to an array and do following: arrayObjectAtIndex.0, arrayObjectAtIndex.1, arrayObjectAtIndex.2, arrayObjectAtIndex.3.
But thats look not good, and that objects may be nil, so i prefer NSString to hold data.
So, how could i write it in a single lane?
UPDATE:
There is the method i want to use to set text for UILabel:
-(void)setLikeLabelText:(UILabel*)label{
//Likes
NSString* likersCount = [self.photosDictionary valueForKeyPath:#"likes.count"];
NSString* likersRecent = [self.photosDictionary valueForKeyPath:#"likes.data.username"];
NSString *textString = [NSString stringWithFormat:#"%# - amount of people like it, recent "likes": %#", likersCount, likersRecent];
label.text = textString;
NSLog(#"text String is %#", textString);
}
valueForKeyPath: returns an NSArray, not an NSString. Whilst you've declared likersCount and likersRecent as instances of NSString, they're actually both arrays of values. You should be able to do something like the following to construct a string:
NSArray* likersRecent = [self.photosDictionary valueForKeyPath:#"likes.data.username"];
NSString *joined = [likersRecent componentsJoinedByString:#"\", \""];
NSString *result = [NSString stringWithFormat:#"\"%#\"", joined];
NSLog(#"Result: %#", result);
componentsJoinedByString: will join the elements of the array with ", ", and then the stringWithFormat call will add a " at the beginning and end.
The statement is incorrect, the internal quote marks (" that you want to display) need to be escaped:
NSString *textString = [NSString stringWithFormat:#"%# - amount of people like it, recent \"likes\": %#", likersCount, likersRecent];
If somebody curious how i fix it, there it is:
for (int i =0; i < [likersRecent count]; i++){
stringOfLikers = [stringOfLikers stringByAppendingString:[NSString stringWithFormat:#" %#", [likersRecent objectAtIndex:i]]];
}
Not using commas or dots though.

iOS: NSNumberFormatter doesn't convert string back to NSNumber

I am using following NSNumberFormatter to add commas and symbol in the currency value.
self.currencyFormatter = [NSNumberFormatter new];
self.currencyFormatter.numberStyle = NSNumberFormatterCurrencyStyle;
self.currencyFormatter.currencySymbol = #"£";
self.currencyFormatter.currencyCode = #"GBP";
self.currencyFormatter.roundingMode = NSNumberFormatterRoundHalfUp;
self.currencyFormatter.maximumFractionDigits = 0;
Usage:
self.principleAmountTextField.text = [self.currencyFormatter stringFromNumber:[NSNumber numberWithInteger:100000]];
This displays £100,000 as expected. Now if I insert two more digits (text becomes £100,00096) in textfield and try to convert string to Integer I get 0! Basically following line returns 0. I have no idea how to deal with this issue.
NSLog(#"%d", [[self.currencyFormatter numberFromString:#"£100,00096"] integerValue]);
FYI I have custom inputview to textfield which just allows numbers to enter into textfield. In Did Edit End even I format number and display with comma.
You need to remove the commas for this to work, you can still show them in your text field but you should strip them out before you pass the string to the formatter. Something like this:
NSString *userInput = #"£100,00096";
userInput = [userInput stringByReplacingOccurrencesOfString:#"," withString:#""];
NSLog(#"%ld", (long)[[currencyFormatter numberFromString:userInput] integerValue]);
100,00096 isn't correct...
Do you mean one of these?
[[self.currencyFormatter numberFromString:#"£10000096"] integerValue]
[[self.currencyFormatter numberFromString:#"£100,000.96"] integerValue]
[[self.currencyFormatter numberFromString:#"£100000.96"] integerValue]
[[self.currencyFormatter numberFromString:#"£10,000,096"] integerValue]
My final code for the reference. The number with currency symbol also an invalid! Following takes care of everything.
NSCharacterSet *doNotWant = [NSCharacterSet characterSetWithCharactersInString:[NSString stringWithFormat:#"%#%#", self.currencyFormatter.groupingSeparator, self.currencyFormatter.currencySymbol]];
self.amountTextField.text = [[self.amountTextField.text componentsSeparatedByCharactersInSet:doNotWant] componentsJoinedByString:#""];
self.amountTextField.text = [NSString stringWithFormat:#"£%#", self.amountTextField.text];
NSUInteger amount = [[self.currencyFormatter numberFromString:self.amountTextField.text] integerValue];
self.amountTextField.text = [self.currencyFormatter stringFromNumber:[NSNumber numberWithInteger:amount]]

Removing last characters of NSString until it hits a separator

I've got a string that shows the stock amount using "-" as separators.
It's built up like this: localStock-wareHouseStock-supplierStock
Now I want to update the supplierStock at the end of the string, but as you can see in the code below it goes wrong when the original string returns more than a single-space value (such as 20).
Is there a way to remove all characters until the last "-" (or remove characters after the second "-")?
NSMutableString *string1 = [NSMutableString stringWithString: p1.colorStock];
NSLog(#"string1: %#",string1);
NSString *newString = [string1 substringToIndex:[string1 length]-2];
NSLog(#"newString: %#",newString);
NSString *colorStock = [NSString stringWithFormat:#"%#-%#",newString,p2.supplierStock];
NSLog(#"colorstock: %#",colorStock);
p1.colorStock = colorStock;
NSLog1
string1: 0-0-0
newString: 0-0
colorstock: 0-0-20
NSLog2
string1: 0-0-20
newString: 0-0-
colorstock: 0-0--20
EDIT: Got it working thanks to Srikar!
NSString *string1 = [NSString stringWithString: p1.colorStock];
NSLog(#"string1: %#",string1);
NSString *finalString = [string1 stringByReplacingOccurrencesOfString:[[string1 componentsSeparatedByString:#"-"] lastObject] withString:p2.supplierStock.stringValue];
NSLog(#"finalString: %#",finalString);
p1.colorStock = finalString;
Why not use componentsSeparatedByString followed by lastObject ?
NSString *supplierStock = [[string1 componentsSeparatedByString:#"-"] lastObject];
The above works if the "stock amount" is always in sets of 3's separated by a "-". Also since you always want supplierStock, lastObject is perfect for your needs.
Of course after splitting string1 with - you get a NSArray instance and you can access the individual components using objectAtIndex:index. So if you want localStock you can get by
NSString *localStock = [[string1 componentsSeparatedByString:#"-"] objectAtIndex:0];
I would suggest splitting the string into the 3 parts using [NSString componentsSeparatedByString:#"-"] and then building it back up again:
NSArray *components = [p1.colorStock componentsSeparatedByString:#"-"];
p1.colorStock = [NSString stringWithFormat:#"%#-%#-%#",
[components objectAtIndex:0],
[components objectAtIndex:1],
p2.supplierStock];
With a string that looks like
NSString *myString = #"Hello-World";
you can separate it with the componentsSeparatedByString: method of the NSString object as
NSArray *myWords = [myString componentsSeparatedByString:#"-"];
The myWords - array will then contain the two NSString objects Hello and World.
To access the strings:
NSString *theHelloString = [myWords objectAtIndex:0];
NSString *theWorldString = [myWords objectAtIndex:1];
Hope it helps!
None of these examples show how to do this if you are unaware of how many of these separator occurrences you're going to have in the original string.
Here's what I believe the correct the correct code should be for dismantling the original string and rebuilding it until you reach the final separator, regardless of how many separators it contains.
NSString *seperator = #" ";
NSString *everythingBeforeLastSeperator;
NSArray *stringComponents = [originalString componentsSeparatedByString:seperator];
if (stringComponents.count!=0) {
everythingBeforeLastSeperator = [stringComponents objectAtIndex:0];
for (int a = 1 ; a < (stringComponents.count - 1) ; a++) {
everythingBeforeLastSeperator = [NSString stringWithFormat:#"%#%#%#", everythingBeforeLastSeperator, seperator, [stringComponents objectAtIndex:a]];
}
}
return everythingBeforeLastSeperator;

How to right pad a string using stringWithFormat

I would like to be able to right align a string using spaces. I have to be able to use the stringWithFormat: method.
So far I have tried the recommended format and it does not seem to work: [NSString stringWithFormat:#"%10#",#"test"].
I would expect this to return a string that has six spaces followed by "test" but all I am getting is "test" with no spaces.
It appears that stringWithFormat ignores the sizing requests of the %# format specifier. However, %s specifier works correctly:
NSString *test = #"test";
NSString *str = [NSString stringWithFormat:#"%10s", [test cStringUsingEncoding:NSASCIIStringEncoding]];
NSLog(#"'%#'", str);
This prints ' test'.
It's C style formatting. %nd means the width is n.
check following code.
NSLog(#"%10#",[NSString stringWithFormat:#"%10#",#"test"]);
NSLog(#"%#",[NSString stringWithFormat:#" %#",#"test"]);
NSLog(#"%10#", #"test");
NSLog(#"%10s", [#"test" cStringUsingEncoding:[NSString defaultCStringEncoding]]);
NSLog(#"%10d", 1);
NSString *str = #"test";
int padding = 10-[str length]; //6
if (padding > 0)
{
NSString *pad = [[NSString string] stringByPaddingToLength:padding withString:#" " startingAtIndex:0];
str = [pad stringByAppendingString:str];
}
NSLog(#"%#", str);

How can i append a space in each side of a string?

i have a NSString object named as myString.i need to append a space in each side of my string.
can any one tell me the good way to do it?
myString = [NSString stringWithFormat:#" %# ", myString];
NSString *myNewString = [NSString stringWithFormat: #" %# ", myString];
Then you can do it in this way.
NSString *s = [[NSString alloc]initWithFormat:#" %# ",str];

Resources