2011-01-25 27 views
65

Quiero convertir stringdata a NSInteger.¿Convierte NSString a NSInteger?

+2

Si google que usted puede conseguir fácilmente la respuesta en el primer golpe en sí – KingofBliss

+19

Debe aceptar las respuestas a sus preguntas. – BoltClock

+3

¿En qué punto se "subastan" las preguntas abandonadas como esta para que la comunidad compre con puntos de reputación ... hmmm :-) –

Respuesta

131

Si la cadena es una representación legible por humanos de un número, usted puede hacer esto:

NSInteger myInt = [myString intValue];
+53

Creo que el lado derecho de la expresión debe ser [myString integerValue], ¿no? –

+0

'[myString intValue]' es un lado oscuro ahaha –

+4

intValue devuelve un int, integerValue devuelve un NSInteger. int es siempre un tipo int, pero NSInteger cambia los tipos para el dispositivo compilado. Hay más sobre eso, pero se recomienda usar NSInteger siempre que sea posible. –

71

[myString intValue] devuelve un "int" cType

[myString integerValue] devuelve un NSInteger.

En la mayoría de los casos encuentro estas sencillas funciones mirando las referencias de clase de manzanas, la forma más rápida de hacerlo es hacer clic en el botón [opción] y hacer doble clic en las declaraciones de clase (en este caso NSString).

+2

consejo simple y util. :) –

1
int myInt = [myString intValue]; 
NSLog(@"Display Int Value:%i",myInt); 
18

He encontrado que esta es la respuesta correcta.

NSInteger myInt = [someString integerValue]; 
-3
NSString *string = [NSString stringWithFormat:@"%d", theinteger]; 
+0

Pidió el reverso de esto. – Lev

6
NSNumber *tempVal2=[[[NSNumberFormatter alloc] init] numberFromString:@"your text here"]; 

vuelve NULL si la cadena o devuelve NSNumber

NSInteger intValue=[tempVal2 integerValue]; 

rendimientos número entero de NSNumber

0

esto es más seguro que IntegerValue:

-(NSInteger)integerFromString:(NSString *)string 
{ 
    NSNumberFormatter *formatter=[[NSNumberFormatter alloc]init]; 
    [formatter setNumberStyle:NSNumberFormatterDecimalStyle]; 
    NSNumber *numberObj = [formatter numberFromString:string]; 
    return [numberObj integerValue]; 
}