NSData appendBytes,添加字符串

时间:2013-08-14 12:46:25

标签: objective-c nsdata

我正在尝试根据交换机创建NSData,但是我在向方法appendBytes添加选项时遇到了问题。添加NSString test会给我一个错误。

示例:

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

知道我该怎么做吗?

1 个答案:

答案 0 :(得分: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];
}

更新

看来你需要C字符串。