2012-05-16 56 views
5

我試圖給一個NSUInteger類型分配一個類型爲'long long'的變量,那麼正確的方法是什麼?隱式轉換失去了整數精度:'long long'到'NSInteger'(又名'int')

我的代碼行:

expectedSize = response.expectedContentLength > 0 ? response.expectedContentLength : 0; 

其中​​的類型是NSUInteger和返回類型的response.expectedContentLength類型是 'long long' 的。變量response的類型爲NSURLResponse

顯示的編譯錯誤是:

語義問題:隱式轉換損失整數精度: '長 長' 到 'NSUInteger'(又名 '無符號整型')

+1

你可以做一個明確的演員,或者你是否知道這個問題,而不是你的問題而不是「如何」?以下是顯式演員陣容: 'expectedSize = response.expectedContentLength> 0? (NSUInteger)response.expectedContentLength:0;' – Clafou

回答

5

這真的只是一個演員,與一些範圍檢查:

const long long expectedContentLength = response.expectedContentLength; 
NSUInteger expectedSize = 0; 

if (NSURLResponseUnknownLength == expectedContentLength) { 
    assert(0 && "length not known - do something"); 
    return errval; 
} 
else if (expectedContentLength < 0) { 
    assert(0 && "too little"); 
    return errval; 
} 
else if (expectedContentLength > NSUIntegerMax) { 
    assert(0 && "too much"); 
    return errval; 
} 

// expectedContentLength can be represented as NSUInteger, so cast it: 
expectedSize = (NSUInteger)expectedContentLength; 
+0

'<0'檢查不正確。值-1意味着「沒有期望可以達到預期的內容長度」(見NSURLResponse.h) –

+0

@Dmitry添加案例爲例。這是一個非常具體的實現細節,可能會被捕獲。它是爲了展示這個過程,而不是一個完美和完整的實現(它現在還不是)。 – justin

11

你可以嘗試與NSNumber的轉換:

NSUInteger expectedSize = 0; 
    if (response.expectedContentLength) { 
    expectedSize = [NSNumber numberWithLongLong: response.expectedContentLength].unsignedIntValue; 
    } 
相關問題