0

目前,我有许多实例方法用于生成一些数据,我想为单个方法更改这些数据,该方法接受我传递给它的输入,编译器告诉我数组初始化器必须是初始化器列表或字符串文字。

我将字符串传递给这样的方法:-

  [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]);

     }
4

1 回答 1

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"];
于 2013-03-26T13:46:49.713 回答