how append nsdata

老子叫甜甜 提交于 2019-12-10 13:24:26

问题


how i could append nsdata, i would append lenght data on first message to send on socket i use code like this but error on runing.

int lendata = [message length];
NSData *firstdata = [NSData dataWithBytes: &lendata length: sizeof(lendata)];
NSData *mdata = [message dataUsingEncoding:NSUTF8StringEncoding];
NSMutableData *seconddata = [NSData dataWithData:mdata];
[firstdata appendData:secondata];

please tell if there is another way Thanks for your help.


回答1:


Glancing into my crystal ball:

  1. You are declaring seconddata as an NSMutableData instance, but then you initialize it using [NSData dataWithData:] instead of [NSMutableData dataWithData:], so seconddata won't be mutable in the end and you cannot append to it.

  2. You are trying to append to firstdata, which is not mutable either.

Solution: make firstdata mutable:

NSMutableData *firstdata = [NSMutableData dataWithBytes: &lendata
                                                 length: sizeof(lendata)];
[firstData appendData:[message dataUsingEncoding:NSUTF8StringEncoding]];

Then you can safely drop mdata and seconddata as they are not needed anymore.




回答2:


 NSMutableData *first_data = [NSMutableData dataWithContentsOfURL:self.firstURL];
 NSMutableData *second_data = [NSMutableData dataWithContentsOfURL:self.secondURL];
 [first_data appendData:second_data];
 [first_data writeToURL:url atomically:YES]; 

check above code for append



来源:https://stackoverflow.com/questions/6042376/how-append-nsdata

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