Vahid Hashemi
Vahid Hashemi

Reputation: 5240

EXC_BAD_ACCESS when initialising an NSString

I want to initialise an NSString with a character with length of 1, but I get an error. Here's my code:

for(int i=0;i<[word length];i++)
    {

        letterMap = [self stringToAscii:[word substringWithRange:NSMakeRange(i, 1) ]];
        NSInteger codec = (letterMap + shifter) % 26;
        unichar ch = [self asciiToString:codec];

        NSString * codedLetter = [NSString stringWithCharacters:ch length:[ch length]];

    }

Upvotes: 0

Views: 223

Answers (1)

Ben Zotto
Ben Zotto

Reputation: 71058

unichar isn't an ObjC object, it's a primitive C type (or typedef) for a single unicode character. You need to call the NSString method (which can take multiple characters in a C-like array) like this:

NSString * codedLetter = [NSString stringWithCharacters:&ch length:1];

(There are two problems in your line of code: first that you're passing the value of a unichar as the first argument, instead of a pointer to it, and the second that you're trying to call -length on something that's not an ObjC object, or even a pointer. It's blowing up due the latter when it tries to send a message to some random memory address.)

Upvotes: 4

Related Questions