0

I know I am probably missing something pretty basic here, but I am trying to convert a number entered on a UITextField from a NSString into a NSNumber as follows:

self.currentServer.port = [NSNumber numberWithInt:[addressPortTextField.text doubleValue]];
NSLog(@"Port: %@ / %@", addressPortTextField.text, self.currentServer.port);

The number in self.currentServer.port is 50000

The NSLog shows the following:

Port: 50000 / -15536

I don't get what I am doing wrong here? I've tried with doubleValue, intValue, integerValue.

* I found the Problem **

self.currentServer.port is a coredata field of type Integer16. 50000 is to large for that field size, I updated the database to Integer32 and all is well now.


Rob
  • 757
  • 1
  • 10
  • 26
  • 1
    Try using NSNumberFormatter, as [this answer][1] suggests. [1]: http://stackoverflow.com/questions/1448804/how-to-convert-an-nsstring-into-an-nsnumber – Jim Nov 09 '11 at 23:30
  • 1
    Why do you say that `self.currentServer.port` is 50000 when it is printing `-15536`? What makes you think it has 50000? If I do `NSLog(@"%@", [NSNumber numberWithInt:[@"50000" intValue]]);` it correctly prints 50000 – Paul.s Nov 09 '11 at 23:34
  • You say you tried `intValue` and it didn't work? Are you sure? This should work: `[NSNumber numberWithInt:[addressPortTextField.text intValue]]` – Abhi Beckert Nov 10 '11 at 00:25
  • The self.currentServer.port field is a core database field defined as NSNumber elsewhere. I tried both numberWithInt and IntValue as well as numberWithInteger and integerValue. No difference. The code works with smaller numbers, like 8080 for example. – Rob Nov 10 '11 at 01:30

2 Answers2

1

This line is wrong:

 self.currentServer.port = [NSNumber numberWithInt:[addressPortTextField.text doubleValue]];

and can be the source of the problem. You are converting the text to double and then saving the value in an int. If you try:

self.currentServer.port = [NSNumber numberWithInteger:[addressPortTextField.text integerValue]];

it is also important how have you defined the currentServer.port.

alinoz
  • 2,822
  • 22
  • 38
  • 1
    To be exact, you should use `numberWithInteger` and `integerValue` or `numberWithInt` and `intValue`. The former uses the `NSInteger` type, the latter uses the `int` type. It doesn't matter on iOS, there they are both 32bit signed integers, but on MacOS, int is 32bit and long is 64bit. (If you have a 64bit CPU) – Jakob Egger Nov 10 '11 at 00:09
0

self.currentServer.port = [NSNumber numberWithInt:[addressPortTextField.text doubleValue]];

Note that you are getting a double value from the text field, is that really what you want? Then calling numberWithInt on the double value.

What you probable want is self.currentServer.port = [NSNumber numberWithInt:[addressPortTextField.text integerValue]];

zaph
  • 111,848
  • 21
  • 189
  • 228