问题
I have a problem: I used below codes to get data from NSData, but I want to get data from [0;2048] bytes. If my data > 2048*strong text*, it can run fine but if my data < 2048
, it'll wrong. So that I want to add more some space at last if my data < 2048
to enough 2048 bytes. Can you help me? Thanks so much.
NSData *data = [NSData dataWithBytes:[arrayText UTF8String] length:[arrayText lengthOfBytesUsingEncoding:NSUTF8StringEncoding]];
NSData *datawrite = [data subdataWithRange:NSMakeRange(0, 2048)];
Above code is work fine if data > 2048 bytes
, if data < 2048 bytes
, my MAC app hangs. Please give me any suggestion. Thanks in advance
回答1:
Ok, this will copy as many bytes as are available (up to 2048) from data
. If the result is < 2048 bytes, the new data will be padded to 2048 bytes.
NSMutableData * datawrite = [ data subdataWithRange:(NSRange){ 0, MIN( 2048, data.length ) } ] mutableCopy ] ;
[ datawrite setLength:2048 ] ;
BUT: Can you tell us the broader application? This seems like a strange use case and I'd like to understand more.
来源:https://stackoverflow.com/questions/18525103/how-can-add-more-space-if-nsdata-fixed-size-in-cocoa