2013-03-25 81 views
0

目前我有一些实例方法用于生成一些数据,我想改变一个方法,该方法接受我传递给它的输入,编译器告诉我认为数组初始值设定项必须是初始化程序列表或字符串文字。从const无符号字符的XCode IOS方法输入数组

林传递字符串像这样的方法: -

[self buildrawdata2:(const unsigned char *)"0ORANGE\0"]; 

下面是当数组使用字符串设定为“0ORANGE \ 0”,我传过来的字符串也不翼而飞,其工作方式方法在“\ 0”结尾,我相信这是因为它的控制字符/转义序列,反正是有保留这一点,并通过它像硬编码下面的字符串: -

- (void)buildrawdata2:(const unsigned char *)inputString2; 

{ 
    NSLog(@"ViewController::buildrawdata2"); 
    NSLog(@"ViewController::buildrawdata2 - inputstring2: %s", inputString2); 

    //this works when set like this 
    const unsigned char magic2[] = "0ORANGE\0"; 

    const uint8_t pattern1 = {0xFC}; 
    const uint8_t pattern2 = {0xE0}; 

    uint8_t rawdata2[56]; 
    uint8_t index = 0; 

    int byte = 0; 
    int bit = 0; 

    while (magic2[byte] != 0x00) { 

     while (bit < 8) { 

     if (magic2[byte] & (1<<bit)) { 
      //add pattern2 to the array 
      rawdata2[index++] = pattern2; 
     }else{ 
      //add pattern1 to the array 
      rawdata2[index++] = pattern1; 
     } 

     // next bit please 
     bit++; 
     } 

     //next byte please 
     byte++; 

     //reset bit index 
     bit = 0; 

     } 

     NSLog(@"buildrawdata2::RawData %@", [NSData dataWithBytes:rawdata2 length:56]); 

    } 

回答

0

貌似我曾找出解决办法,我会很乐意听到别人对这种方法的看法或建议离子来改善它。

而不是采取传递给方法的字符串,并试图直接更新数组初始值设定项我使用字符串来确定应使用哪个数组初始值设定项。为了这个工作,我必须在if块之前创建一个指针,这样我才能从if块中为它分配字符串。

const unsigned char *magic = NULL; 

if (inputString == @"0APPLES") { magic = (const unsigned char*) "0APPLES\0";} 
else if (inputString == @"0ORANGE") { magic = (const unsigned char*) "0ORANGE\0";} 

最近也试过这样的,它也是工作: -

const unsigned char apples[] = "0APPLES\0"; 
const unsigned char orange[] = "0ORANGE\0"; 
const unsigned char *magic; 

if (inputString2 == @"0APPLES") { magic = apples;} 
else if (inputString2 == @"0ORANGE") { magic = orange;} 

的方法就可以这样调用: -

[self buildrawdata1:@"0APPLES"]; 
[self buildrawdata1:@"0ORANGE"]; 
相关问题