Wrong conversion from number to string
How can I convert a number into string.
Here is my code:
NSDictionary *myDict = [NSDictionary dictionaryWithObjectsAndKeys:@"1100", @"myKey",nil];
开发者_StackOverflow社区
NSString *myData = [NSString stringWithFormat:@"%d", [myDict valueForKey:@"myKey"]];
The output in myData is not 1100 but some random number. What is wrong here.
The number that you're storing already is in form of a string (note the quotes: @"…").
What you likely want is something like this:
NSDictionary *myDict = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInteger:1100], @"myKey",nil];
NSString *myData = [NSString stringWithFormat:@"%d", [[myDict objectForKey:@"myKey"] integerValue]];
Let's go thru that code step by step:
- We create an NSNumber object holding 1100 via
[NSNumber numberWithInteger:1100]
- We create an NSDictionary object with said number object as value for key
@"myKey"
- We request the value for key
@"myKey"
frommyDict
via[myDict objectForKey:@"myKey"]
, which will return the NSNumber instance that we had passed to it previously. - We then request the integer value (NSInteger, which is an abstraction around int/long) of the received NSNumber instance via
[… integerValue]
- We pass the NSInteger value to
[NSString stringWithFormat:@"%d", …]
Alternatively you could skip step 4 and change @"%d" to @"%@", which will print the same. In case of simple integer values at least. For floating point values you would not want to print NSNumbers directly via @"%@" as you'd loose control over display of decimal precision.
Note that we use objectForKey:
, not valueForKey:
, here is why: https://stackoverflow.com/search?q=valueForKey%20objectForKey
You could have made the same string by changing your code to this:
NSDictionary *myDict = [NSDictionary dictionaryWithObjectsAndKeys:@"1100", @"myKey",nil];
NSString *myData = [NSString stringWithFormat:@"%@", [myDict objectForKey:@"myKey"]];
The reason though, why would not want to do this: It is (in general) bad practice to store numeric **(or just about any other non-textual) values as strings**.
%d
is a specifier for integer values while you are inserting @"1100"
, which is a NSString
, inside the dictionary.
Change the specifier with %@
and it will work.. or if you want to place the number itself you will have to wrap it with a Obj-C object (like NSNumber
) inside the dictionary.
Both other answers are correct, but...
You appear to want:
NSDictionary *myDict = [NSDictionary dictionaryWithObjectsAndKeys:@"1100", @"myKey",nil];
NSString *myData = [myDict valueForKey:@"myKey"];
There's no need to do the +stringWithFormat:
dance because you're already storing the value as a string (@"..."
means that it's a string).
精彩评论