0

Possible Duplicate:
How do I convert a string into an integer in objective C?

I want to take a string from an UITextField object and convert it into an integer scalar type.

NSInteger *ageOfTheUser;
NSString *string;
self.string=age.text;
ageOfTheUser=(int)string;

I am getting a warning at ageOfTheUser with 'assigment makes pointer from string cast'.

Community
  • 1
  • 1
Faizan Tanveer
  • 335
  • 6
  • 17

4 Answers4

4

If your string is already set to a number, you can simply do:

ageOfTheUser = [string integerValue];

and you're all set.

There's a difference between intValue (which is meant to go to a type of int) and integerValue (which goes to your declared type of NSInteger).

One more thing, get rid of the pointer after your NSInteger declaration (i.e. instead of NSInteger * ageOfTheUser;, do NSInteger ageOfTheUser;).

Michael Dautermann
  • 88,797
  • 17
  • 166
  • 215
2
ageOfTheUser = [string intValue];

Note you can assign an int to an NSInteger without any additional syntax.

Duncan Babbage
  • 19,972
  • 4
  • 56
  • 93
  • this isn't correct because NSString's intValue method returns an `int`, not a `NSInteger` – Michael Dautermann Dec 09 '11 at 19:13
  • Really? Have you tried this and found that it does not work? :) – Duncan Babbage Dec 09 '11 at 19:18
  • Oh sure, it does work (for 32-bit number/architecture). 64-bit is somewhat different. [Here's a related question that you may find illuminating](http://stackoverflow.com/questions/5870867/why-is-there-an-nsinteger) and [another one](http://stackoverflow.com/questions/4445173/when-to-use-nsinteger-vs-int). – Michael Dautermann Dec 09 '11 at 19:25
2

Simple as this:

int myAgeInt = [@"30" intValue];
Williham Totland
  • 28,471
  • 6
  • 52
  • 68
Louie
  • 5,920
  • 5
  • 31
  • 45
1

First of all NSInteger is typedef'd to long int, so it's not an object. Just use:

NSInteger ageOfTheUser;

Converting NSString to int is very simple:

ageOfTheUser = [self.string intValue];
Sanjay Chaudhry
  • 3,181
  • 1
  • 22
  • 31