How to convert NSNumber to NSString - objective-c

So I have an NSArray "myArray" with NSNumbers and NSStrings. I need them in another UIView so i go like this:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
DetailViewController *details = [[DetailViewController alloc] initWithNibName:#"DetailView" bundle:nil];
details.subjectText = [[myArray objectAtIndex:indexPath.row] objectForKey:#"subject"];
The subjectText works.
But how can I get the NSNumbers out of it? (I actually need them as strings...)
I would convert a NSString out of a NSNumber like this:
NSString *blah = [NSNumber intValue]. But I don't know how to set it up in the code above...

Try:
NSString *myString = [NSNumber stringValue];

You can do it with:
NSNumber *myNumber = #15;
NSString *myNumberInString = [myNumber stringValue];

//An example of implementation :
// we set the score of one player to a value
[Game getCurrent].scorePlayer1 = [NSNumber numberWithInteger:1];
// We copy the value in a NSNumber
NSNumber *aNumber = [Game getCurrent].scorePlayer1;
// Conversion of the NSNumber aNumber to a String with stringValue
NSString *StringScorePlayer1 = [aNumber stringValue];

or try NSString *string = [NSString stringWithFormat:#"%d", [NSNumber intValue], nil];

The funny thing is that NSNumber converts to string automatically if it becomes a part of a string. I don't think it is documented.
Try these:
NSLog(#"My integer NSNumber:%#",[NSNumber numberWithInt:184]);
NSLog(#"My float NSNumber:%#",[NSNumber numberWithFloat:12.23f]);
NSLog(#"My bool(YES) NSNumber:%#",[NSNumber numberWithBool:YES]);
NSLog(#"My bool(NO) NSNumber:%#",[NSNumber numberWithBool:NO]);
NSString *myStringWithNumbers = [NSString stringWithFormat:#"Int:%#, Float:%# Bool:%#",[NSNumber numberWithInt:132],[NSNumber numberWithFloat:-4.823f],[NSNumber numberWithBool:YES]];
NSLog(#"%#",myStringWithNumbers);
It will print:
My integer NSNumber:184
My float NSNumber:12.23
My bool(YES) NSNumber:1
My bool(NO) NSNumber:0
Int:132, Float:-4.823 Bool:1
Works on both Mac and iOS
This one does not work:
NSString *myNSNumber2 = [NSNumber numberWithFloat:-34512.23f];

In Swift you can do like this
let number : NSNumber = 95
let str : String = number.stringValue

In Swift 3.0
let number:NSNumber = 25
let strValue = String(describing: number as NSNumber)
print("As String => \(strValue)")
We can get the number value in String.

Related

changing a string to double returning one

I have stored a value 1/129600.0 in a plist as a string.
I am able to retrieve it as a string but when i am trying to convert it as a double i am getting it as 1.0.I have also tried CFString
NSString *value = [[self array]objectAtIndex:m];
double a = [value doubleValue];
NSLog(#"%#",value);
NSLog(#"%f",a);
and in log the returned values are
1/129600.0 and 1.0
This code works fine, I tried it in xCode:
NSString *equation = [[self array]objectAtIndex:m];
NSExpression *result = [NSExpression expressionWithFormat:equation];
NSNumber *a = [result expressionValueWithObject:nil context: nil];
NSLog(#"%#",result);
NSLog(#"%.10f",[a doubleValue]);
I guess 1/129600.0 is not a valid number.
Try to create an expression and create an NSNumber from it:
NSString *equation = [[self array]objectAtIndex:m];
NSNumber *a = [[NSExpression expressionWithFormat:equation] expressionValueWithObject:nil context:nil];
double a = [result doubleValue];
NSLog(#"%f", a);
1/129600.0 is not a valid representation for a number in most programming languages, including ObjC. You need to parse the string and interpret it yourself.
Try this
NSString *value = [[self array]objectAtIndex:m];
NSArray *arr = [value componentsSeparatedByString:#"/"];
double a;
if ([arr count] == 2)
{
a = [arr objectAtIndex:0]/[arr objectAtIndex:1];
}
NSLog(#"%#",value);
NSLog(#"%f",a);

Saving int values to Array when app closes

I have an Iphone app that uses alot of int values that will increment on IBActions, I want to save the int values to an array when the app closes so that these values are stores and used when the app is reopened. I am not sure how to write int values into an array. Functionally, I am getting this to wort with text field but not integers i.e.
int count;
code used:
NSArray *values = [[NSArray alloc] initWithObjects:fieldOne.text,fieldTwo.text,count, nil];
This gives an "Assignment makes integer from pointer without cast" message.
Is there anyway to write already stored int values into and array?
code I used is as follows:
I thinks its ok until the calling the data into the array. I have commented out some failed efforts
-(NSString *) saveFilePath{
NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
return [[path objectAtIndex:0] stringByAppendingPathComponent:#"savefile.plist"];
}
-(void) applicationDidEnterBackground: (UIApplication *) application{
//NSNumber *num = [[NSNumber alloc]initWithInt:count];
NSArray *values = [[NSArray alloc] initWithObjects:fieldOne.text,fieldTwo.text,[NSNumber numberWithInt:count],nil];
[values writeToFile:[self saveFilePath] atomically:YES];
[values release];
}
- (void)viewDidLoad {
//NSNumber *num = [[NSNumber alloc]initWithInt:count];
NSString *myPath = [self saveFilePath];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:myPath];
if (fileExists) {
NSArray *values = [[NSArray alloc] initWithContentsOfFile:myPath];
fieldOne.text = [values objectAtIndex:0];
fieldTwo.text = [values objectAtIndex:1];
//[NSNumber count intValue] = [values objectAtIndex:2];
[values release];
}
UIApplication *myApp = [UIApplication sharedApplication];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector (applicationDidEnterBackground:)name:UIApplicationDidEnterBackgroundNotification object:myApp];
[super viewDidLoad];
}
Thank you for your help.
You should use NSNumber so something like:
NSNumber *num = [NSNumber numberWithInt:int];
which will give you an object containing your int. To read back from it, use [num intValue]
Create a NSNumber object with your count as its value and put the object into your array. NSArrays need to be arrays of objects.
Container classes work with Objects not fundamental types. You have to wrap fundamental types in NSNumber (numbers) , NSData etc.

Make variable name out of NSString

I have got a for loop where 9 hexagons (hexagon1 through hexagon9) have to be created... But I cannot use hexString as the name of the Sprite because it is a NSString, right ? So how would I make it right ?
hexString [<- I want the for loop to generate "hexagon1", then "hexagon2" and so on instead of the NSString] = [self createHexagon:ccp(xVal,yVal) :i];
int hexCount = [[[itemPositions valueForKey:myString]valueForKey:#"hexposition"] count];
for (int i=1;i<=hexCount;i++){
NSString *hexString = [NSString stringWithFormat:#"hexagon%d",i];
NSNumber *generatedXVal = [[[[itemPositions valueForKey: myString ]valueForKey:#"hexposition"] valueForKey: hexString]valueForKey: #"xVal"];
int xVal = [generatedXVal integerValue];
NSNumber *generatedYVal = [[[[itemPositions valueForKey: myString ]valueForKey:#"hexposition"] valueForKey: hexString ]valueForKey: #"yVal"];
int yVal = [generatedYVal integerValue];
hexString = [self createHexagon:ccp(xVal,yVal) : i];
NSLog(#"%#", hexString);
}
That would be impossible as you didn't declare the variable. A work around for this would be using an NSArray and saving your data on to the array instead of making a list of variables.
Use NSMutableDictionary.
for (int i=1;i<=hexCount;i++){
NSString *hexString = [NSString stringWithFormat:#"hexagon%d",i];
CCSprite *sprite = [self doSomethingToGetSprite];
[mutableDictionary setObject:sprite forKey:hexString];
}
Later you can iterate over all the sprites in the dictionary using:
for (NSString *key in mutableDictionary) {
CCSprite *sprite = [mutableDictionary objectForKey:key];
[self doStuffWithSprite:sprite];
}
By the way, why are you overwriting hexString that you assign here:
NSString *hexString = [NSString stringWithFormat:#"hexagon%d",i];
With the one here:
hexString = [self createHexagon:ccp(xVal,yVal) : i];
And that method call is an obvious syntax error with the dangling : i part there.
can you use NSSelectorFromString?

how to convert integer to string? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
How to convert from int to string in objective c: example code…
How to convert integer to string in Objective C?
NSArray *myArray = [NSArray arrayWithObjects:[NSNumber numberWithInt:1], [NSNumber numberWithInt:2], [NSNumber numberWithInt:3]];
Update for new Objective-C syntax:
NSArray *myArray = #[#1, #2, #3];
Those two declarations are identical from the compiler's perspective.
if you're just wanting to use an integer in a string for putting into a textbox or something:
int myInteger = 5;
NSString* myNewString = [NSString stringWithFormat:#"%i", myInteger];
If you really want to use String:
NSString *number = [[NSString alloc] initWithFormat:#"%d", 123];
But I would recommend using NSNumber:
NSNumber *number = [[NSNumber alloc] initWithInt:123];
Then just add it to the array.
[array addObject:number];
Don't forget to release it after that, since you created it above.
[number release];
NSString* myNewString = [NSString stringWithFormat:#"%d", myInt];

How to convert nsstring to nsdictionary?

I have gone through following question.
Convert NSString to NSDictionary
It is something different then my question.
My question is as follows.
NSString *x=#"<Category_Id>5</Category_Id><Category_Name>Motos</Category_Name><Category_Picture>http://192.168.32.20/idealer/admin/Picture/icon_bike2009819541578.png</Category_Picture>";
Now I want to convert this into a dictionary, something like this,
dictionary key = Category_Id | value = 5
dictionary key = Category_Name | value = ???
dictionary key = Category_Picture | value = ???
I don't know how to perform this.
Not the fastest implementation, but this would do the trick (and doesn’t require any third party libraries):
#interface NSDictionary (DictionaryFromXML)
+ (NSDictionary *)dictionaryFromXML:(NSString *)xml;
#end
#implementation NSDictionary (DictionaryFromXML)
+ (NSDictionary *)dictionaryFromXML:(NSString *)xml
{
// We need to wrap the input in a root element
NSString *x = [NSString stringWithFormat:#"<x>%#</x>", xml];
NSXMLDocument *doc = [[[NSXMLDocument alloc] initWithXMLString:x
options:0
error:NULL]
autorelease];
if (!doc)
return nil;
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
for (NSXMLElement *el in [[doc rootElement] children])
[dict setObject:[el stringValue] forKey:[el name]];
return dict;
}
#end
If it's XML then you can use an NSXMLParser. If it's not then you can write your own parser.
You could do it with a regular expression... Something like <([^>]+)>([^<]+)</\1> would grab the key into capture 1 and the value into capture 2. Iterate over the matches and build the dictionary.
This uses RegexKitLite:
NSString * x = #"<Category_Id>5</Category_Id><Category_Name>Motos</Category_Name><Category_Picture>http://192.168.32.20/idealer/admin/Picture/icon_bike2009819541578.png</Category_Picture>";
NSString * regex = #"<([^>]+)>([^<]+)</\\1>";
NSArray * cap = [x arrayOfCaptureComponentsMatchedByRegex:regex];
NSMutableDictionary * d = [NSMutableDictionary dictionary];
for (NSArray * captures in cap) {
if ([captures count] < 3) { continue; }
NSString * key = [captures objectAtIndex:1];
NSString * value = [captures objectAtIndex:2];
[d setObject:value forKey:key];
}
NSLog(#"%#", d);