Domanda

Currently I have a number of instance methods for generating some data that I would like to change for a single method that takes an input which I pass to it, the compiler is telling me that the array initializer must be an initializer list or string literal.

Im passing the string to the method like this :-

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

Here is the method that works when the array uses a string set to "0ORANGE\0", the string I pass over is also missing the "\0" from the end, I believe this is because its a control character / escape sequence, is there anyway to retain this and pass it like the string hardcoded below :-

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

     }
È stato utile?

Soluzione

Looks like I have worked out a solution to this, I would be happy to hear others views on this method or suggestions to improve it.

Instead of taking the string passed into the method and trying to directly update the array initializer I used the string to determine which array initializer should be used. For this to work I had to create a pointer before the if block so that I could then assign strings to it from within the if blocks.

 const unsigned char *magic = NULL;

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

Also recently tried this way and its also working :-

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

The method can then be called like this :-

 [self buildrawdata1:@"0APPLES"];
 [self buildrawdata1:@"0ORANGE"];
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top