Gerdinando
Gerdinando

Reputation: 57

NSData appendBytes, adding string

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?

Upvotes: 0

Views: 6868

Answers (1)

sbarow
sbarow

Reputation: 2819

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.

Upvotes: 3

Related Questions