views:

266

answers:

2

I'm attempting conversion of a legacy C++ program to objective-C. The program needs an array of the 256 possible ASCII characters (8-bits per character). I'm attempting to use the NSString method initWithBytes:length:encoding: to do so. Unfortunately, when coded as shown below, it crashes (although it compiles).

NSString*     charasstring[256];
unsigned char char00;
int           temp00;
    for (temp00 = 0; temp00 <= 255; ++temp00)
        {
        char00 = (unsigned char)temp00;
        [charasstring[temp00] initWithBytes:&char00 length:1 encoding:NSASCIIStringEncoding]; 
        }

Please advise what I'm missing. Thank you.

+6  A: 

First, the method is simply initWithBytes:length:encoding and not the NSString::initWithBytes you used in the title. I point this out only because forgetting everything you know from C++ is your first step towards success with Objective-C. ;)

Secondly, your code demonstrates that you don't understand Objective-C or use of the Foundation APIs.

  • you aren't allocating instances of NSString anywhere

  • you declared an array of 256 NSString instance pointers, probably not what you want

  • a properly encoded ASCII string does not include all of the bytes

I would suggest you start here.

bbum
That wasn't the question. I'll try not to react to your condecension.
McPragma
His points are valid, the code as you have it now has the problems he listed.
phoebus
I apologize if you took it as an insult. It wasn't intended to be. The code is so far off base that starting from the Objective-C intro documentation is going to be a productive use of time. And the comment about forgetting C++ is also quite intentional; I've been teaching Objective-C for 2 decades and the students that had the most difficulty were the ones who made assumptions based on C++ (or some other language's) behavior.
bbum
A: 

To solve that specific problem, the following code should do the trick:

NSMutableArray* ASCIIChars = [NSMutableArray arrayWithCapacity:256];
int i;
for (i = 0; i <= 255; ++i)
    {
    [ASCIIChars addObject:[NSString stringWithFormat:@"%c", (unsigned char)i]];
    }

To be used, later on, as follows:

NSString* oneChar = [ASCIIChars objectAtIndex:32]; // for example

However, if all you need is an array of characters, you can just use a simple C array of characters:

unsigned char ASCIIChars [256];
int i;
for (i = 0; i <= 255; ++i)
    {
    ASCIIChars[i] = (unsigned char)i;
    }

To be used, later on, as follows:

unsigned char c = ASCIIChars[32];

The choice will depend on how you want to use that array of characters.

e.James