Ahmed Karmous
Ahmed Karmous

Reputation: 373

Conversion issue from NSNumber to NSString

I'm parsing data from a JSON webservice and adding it to the database so when I insert an int, I have to convert it to NSNumber in this way it's working fine: 24521478

NSString *telephone = [NSString stringWithFormat:@"%@",[user objectForKey:@"telephone"]];
int telephoneInt = [telephone intValue];
NSNumber *telephoneNumber = [NSNumber numberWithInt:telephoneInt];

patient.telephone = telephoneNumber;

but when I want to display it and convert the NSNumber to NSString I'm getting wrong numbers: -30197

NSString *telephoneString = [NSString stringWithFormat:@"%d", [user.telephone intValue], nil];
labelTelephone.text =telephoneString ;

Can someone explain this?

Upvotes: 1

Views: 336

Answers (2)

Paulson Varghese
Paulson Varghese

Reputation: 56

NSNumber comes with dedicated methods for each data type.If you want to convert NSNumber to NSString use:

 NSString *telephoneString = [user.telephone  stringValue];

The issue may coming because of the data type you used for the variable patient.telephone

Upvotes: 2

Hani Ibrahim
Hani Ibrahim

Reputation: 1449

If you have control over the web service, then you should return the telephone number as string in the JSON

Reasons

  1. if the telephone number begin with zero then the NSNumber will remove that zero as it has no value (ex: 00123456789 will be 123456789 which will wrong data)
  2. You will not be able to display the telephone number is a user friendly way by adding "+" and "-"    (ex: +123-456-789)

You really should make the json return the number as string if you have a control over that

Upvotes: 0

Related Questions