Domanda

Ho un numero in un @"15" NSString. Voglio convertire questo per NSUInteger, ma non so come fare ...

È stato utile?

Soluzione

NSString *str = @"15";
// Extract an integer number, returns 0 if there's no valid number at the start of the string.
NSInteger i = [str integerValue];

Se si vuole veramente un NSUInteger, appena lanciato, ma si consiglia di verificare il valore in anticipo.

Altri suggerimenti

La risposta al momento scelto è corretto per NSUInteger. Come Corey Floyd sottolinea un commento sulla risposta selezionata questa non funziona se il valore è maggiore di INT_MAX. Un modo migliore per farlo è quello di utilizzare NSNumber e quindi utilizzando uno dei metodi su NSNumber per recuperare il tipo Sei in interessati, per esempio:.

NSString *str = @"15"; // Or whatever value you want
NSNumber *number = [NSNumber numberWithLongLong: str.longLongValue];
NSUInteger value = number.unsignedIntegerValue;

Tutte queste risposte sono sbagliate su un sistema a 64 bit.

NSScanner *scanner = [NSScanner scannerWithString:@"15"];
unsigned long long ull;
if (![scanner scanUnsignedLongLong:&ull]) {
  ull = 0;  // Or handle failure some other way
}
return (NSUInteger)ull;  // This happens to work because NSUInteger is the same as unsigned long long at the moment.

Prova con 9223372036854775808, che non si adatta in un long long firmato.

si può provare con [string longLongValue] o [string intValue] ..

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top