Search code examples
objective-cnsstringnsstringencoding

Weird error with NSString: No known class method for selector 'stringWithBytes:length:encoding:'


I am attempting to use scanf to assign a value to an NSString, as per the answers to this question by Omar. This is the code, taken straight from progrmr's answer:

char word[40];

        int nChars = scanf("%39s", word);   // read up to 39 chars (leave room for NUL)
        NSString* word2 = [NSString stringWithBytes:word
                                             length:nChars
                                           encoding:NSUTF8StringEncoding];

However, I'm getting an error on the last line that makes absolutely no sense to me:

No known class method for selector 'stringWithBytes:length:encoding:'

What in the world could be causing this error?

And yes, I do have #import <Foundation/Foundation.h> at the top of the file.


Solution

  • NSString does not have a stringWithBytes:length:encoding: class method, but you can use

    NSString* word2 = [[NSString alloc] initWithBytes:word
                                             length:nChars
                                           encoding:NSUTF8StringEncoding];
    

    Note however, that scanf() returns the number of scanned items and not the number of scanned characters. So nChars will contain 1 and not the string length, so you should set nChars = strlen(word) instead.

    A simpler alternative is (as also mentioned in one answer to the linked question)

    NSString* word2 = [NSString stringWithUTF8String:word];