How to add nsdata

how could I add nsdata, I would add length data for the first message to be sent on the socket I use this code, but there is an error at startup.

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]; 

tell me if there is another way Thank you for your help.

+7
source share
2 answers

Look into my crystal ball:

  • You declare seconddata as an instance of NSMutableData , but then you initialize it with [NSData dataWithData:] instead of [NSMutableData dataWithData: ], so seconddata will not change at the end, and you cannot add to it.

  • You are trying to add to firstdata , which is also not changed.

Solution: make firstdata mutable:

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

Then you can safely discard mdata and seconddata as they are no longer needed.

+18
source
  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 to add

+6
source

All Articles