为什么使用subdataWithRange崩溃获得部分数据范围?

时间:2012-01-23 12:14:45

标签: objective-c

我有这段代码:

 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变量,它只包含字节的后半部分

1 个答案:

答案 0 :(得分: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