0

I'm trying to create a NSData depending on a switch, but I'm having trouble adding the options to the method appendBytes. Adding the NSString test gives me an error.

Example:

- (void)selectCenterJustification:(int)option
{
    NSMutableData *data;
    NSString *test;
    switch (option)
    {
        case 0:
            test = @"\x0";
            break;
        case 1:
            test = @"\x1";
            break;
        case 2:
            test = @"\x2";
            break;
    }
    // does not work because of "test"
    [data appendBytes:"\x1b" "a", test length:3];

    // working
    [data appendBytes:"\x1b" "a" "\x1" length:3];
}

Any idea how I can do this?

1 Answer 1

3
NSMutableData *data = [NSmutableData data];
NSString *test = nil;

switch (option) {
    case 0:
        test = @"\x0";
        break;
    case 1:
        test = @"\x1";
        break;
    case 2:
        test = @"\x2";
        break;
    default:
        NSLog(@"[justification]: unknown option");
        break;
}
if (test) {
    [data appendBytes:"\x1b" "a" length:2];
    [data appendBytes:[test cStringUsingEncoding:NSASCIIStringEncoding] length:1];
}

Update

It appears you need C strings.

Sign up to request clarification or add additional context in comments.

8 Comments

make sure to alloc-init data before trying to append to it
Problem isn't appending test, but to add it together with the other data. (see edit in original post)
What do you mean add it together with other data? If I understand correctly you should be creating an instance variable to append data too as opposed to create a local variable of NSMutableData.
Originally data is an instance variable. I just changed it to local so the example will work after copying it :).
Okay updated my answer to use NSMutableString which you can append to then convert to NSData. Hope I understood correctly.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.