Search code examples
objective-cnsmutabledata

How do I add an NSString to NSMutableData?


I cannot figure out how to add my NSString to an NSMutableData structure

this is what I want to achieve, below is hardcoded and works, you can see the number string is what I want to replace with dynamic data from a helper function I have.

NSMutableData *commands = [NSMutableData data];

[commands appendBytes:"\x1b\x62\x06\x02\x02\x20" "09258384394951\x1e\r\n" length:sizeof("\x1b\x62\x06\x02\x02\x20" "09258384394951\x1e\r\n") - 1];

I tried constructing an NSString that would mimic the above exactly as follows

NSString *trNo = [NSString stringWithFormat:@"\"\x1b\x62\x06\x02\x02\x20\" \"%@\x1e\r\n\"", [NWTillHelper getCurrentOrderNumber]];

But this cannot be added to the NSMutableData construct, I tried as below

[commands appendBytes:(__bridge const void * _Nonnull)(trNo) length:sizeof("\x1b\x62\x06\x02\x02\x20" "09258384394951\x1e\r\n") - 1];

How can I create an appendBytes construct in such a way that I can insert my NSString into it and get it to be dynamic?

---- Further clarification -----

I am using the NSData structure to send to a printer

for example the following is the code to cut the label

 // Cut the paper
    [commands appendBytes:"\x1b\x64\x02" length:sizeof("\x1b\x64\x02") - 1];

This is the command for making the text aligned center

// Alignment (Center)
    [commands appendBytes:"\x1b\x1d\x61\x01" length:sizeof("\x1b\x1d\x61\x01") - 1];

As you can see these are plain Hex commands and they work fine as is

The problem I am having is that the command to print a barcode includes a dynamic string in the middle of all the HEX code and I cannot figure out how to get an NSString into the middle of this HEX code.

This is the command to print a barcode, where the barcode contains the numbers 09258384394951, as you can see those are hardcoded below. This code works fine, the printer prints the barcode correctly but the problem is that I cannot hardcode the numbers/characters 09258384394951 I need that to be a variable of some sort and this is where I am stuck.

[commands appendBytes:"\x1b\x62\x06\x02\x02\x20" "09258384394951\x1e\r\n" length:sizeof("\x1b\x62\x06\x02\x02\x20" "09258384394951\x1e\r\n") - 1];

Solution

  • Add the data in 3 steps:

    NSMutableData *commands = [NSMutableData data];
    NSData *orderNumber = [@"09258384394951" dataUsingEncoding:NSUTF8StringEncoding];  // example of order number converted to NSData
    [commands appendBytes:"\x1b\x62\x06\x02\x02\x20" "" length:sizeof("\x1b\x62\x06\x02\x02\x20" "") - 1];  
    [commands appendData:orderNumber];  
    [commands appendBytes:"\x1e\r\n" length:sizeof("\x1e\r\n") - 1];