2012-01-23 25 views
0

我有這樣的代碼:爲什麼使用subdataWithRange崩潰會導致部分數據範圍?

NSMutableData *derivedKey = [NSMutableData dataWithLength:32]; 

// code missing..fill somehow the derivedKey with 32 random bytes 

// This line doesn't crash 
NSData *iv = [derivedKey subdataWithRange:NSMakeRange(0, 32)]; 

..

// This line crashes 
NSData *iv = [derivedKey subdataWithRange:NSMakeRange(16, 32)]; 

任何建議,爲什麼出現這種情況? 似乎以某種方式只能從0的整個範圍 - 32穿過 我想簡單一個新的NSData變量僅包含字節

回答

10

它崩潰的第二一半,因爲NSRangeMake的第二個參數是該範圍的長度。所以你要做的就是從偏移量16開始取32個字節,超過了數據大小(最後一個字節的順序是48)。

那麼簡單,它更改爲:

NSData *iv = [derivedKey subdataWithRange:NSMakeRange(16, 16)]; 

檢查裁判: http://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_Functions/Reference/reference.html#//apple_ref/c/func/NSMakeRange

+0

Oh..I與位置混淆了。非常感謝你 –

相關問題