How can add more space if NSData < fixed size in Cocoa

一个人想着一个人 提交于 2019-12-12 02:52:52

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!