2015-01-01 61 views
0

我正在使用下面的代碼。我可以成功獲取字符串值。但是,如果將其轉換爲NSInteger,則會在前面顯示減號,並且值會更改。我錯過了什麼嗎?將字符串轉換爲大整數值

NSInteger bannerStamp = [[eachDict objectForKey:@"timeStamp"] integerValue]; 
NSLog(@"%@",[eachDict objectForKey:@"timeStamp"]); 
NSLog(@"%d",bannerStamp); 

輸出

2015-01-01 10:44:52.482 SalesApp[24570:60b] 3597478187 
2015-01-01 10:44:54.094 SalesApp[24570:60b] -697489109 
+0

你使用的字符串實際上是一個無符號整數(你應該得到unsignedIntegerValue)? –

+0

@BradBrighton yes它始終是一個正值 –

回答

2

嘗試轉換成很長很長的值

long long bannerStamp = [[eachDict objectForKey:@"timeStamp"] longLongValue]; 
NSLog(@"%@",[eachDict objectForKey:@"timeStamp"]); 
NSLog(@"%lld",bannerStamp); 

下面是32位和64位架構之間的差異,

#if __LP64__ || (TARGET_OS_EMBEDDED && !TARGET_OS_IPHONE) || TARGET_OS_WIN32 || NS_BUILD_32_LIKE_64 
typedef long NSInteger; 
typedef unsigned long NSUInteger; 
#else 
typedef int NSInteger; 
typedef unsigned int NSUInteger; 
#endif 

蘋果文檔鏈接,changes to data types

+1

感謝分享蘋果文檔鏈接。幾個月前我得到了這個問題。我像你解釋過的一樣,謝謝。 – ObjC

1

這就是我得到去了我的頭頂部。檢查此代碼並輸出各種方法。

//******* 
NSLog(@"For SO question"); 
NSDictionary *eachDict = @{ @"timeStamp" : @"3597478187" }; 
NSDecimalNumber *decimalBannerStamp = [NSDecimalNumber decimalNumberWithString:[eachDict objectForKey:@"timeStamp"]]; 
NSInteger bannerStamp = [[eachDict objectForKey:@"timeStamp"] integerValue]; 
uint64_t bannerStampUINT64 = [[eachDict objectForKey:@"timeStamp"] longLongValue]; 
NSLog(@"%@",[eachDict objectForKey:@"timeStamp"]); 
NSLog(@"NSInteger: %u",bannerStamp); 
NSLog(@"uint64_t: %llu",bannerStampUINT64); 
NSLog(@"DecimalObject: %@", decimalBannerStamp); 
NSLog(@"Decimal unsigned value: %lu", (unsigned long)decimalBannerStamp.unsignedIntegerValue); 
NSLog(@"End SO question code"); 
//******* 


2014-12-31 22:14:50.206 PIClient[5112:2296154] For SO question 
2014-12-31 22:14:50.212 PIClient[5112:2296154] 3597478187 
2014-12-31 22:14:50.213 PIClient[5112:2296154] NSInteger: 2147483647 
2014-12-31 22:14:50.213 PIClient[5112:2296154] uint64_t: 3597478187 
2014-12-31 22:14:50.214 PIClient[5112:2296154] DecimalObject: 3597478187 
2014-12-31 22:14:50.215 PIClient[5112:2296154] Decimal unsigned value: 3597478187 
2014-12-31 22:14:50.215 PIClient[5112:2296154] End SO question code 
+0

可能更適合使用uint64_t(這是一個無符號長整數),它在32位和64位系統上都是64位值。 – zaph

+0

如果源數據或轉換後的值的使用結果保證了額外的安全措施,我同意。 –

+0

沒辦法。 NSUInteger bannerStamp = [[eachDict objectForKey:@「timeStamp」] unsignedIntegerValue]; 顯示了相同的結果。 –