0

根据 Omar对这个问题的回答,我正在尝试使用 scanf 为 NSString 分配一个值。这是代码,直接取自 progrmr 的答案:

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

但是,我在最后一行遇到了一个对我来说完全没有意义的错误:

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

到底是什么导致了这个错误?

是的,我确实#import <Foundation/Foundation.h>在文件的顶部。

4

3 回答 3

4

NSString没有stringWithBytes:length:encoding:类方法,但你可以使用

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

但是请注意,这scanf()将返回已扫描项目的数量,而不是已扫描字符的数量。所以nChars将包含1而不是字符串长度,所以你应该设置nChars = strlen(word)

一种更简单的替代方法是(如链接问题的一个答案中所述)

NSString* word2 = [NSString stringWithUTF8String:word];
于 2014-01-06T18:30:51.857 回答
2

NSString 不响应选择器stringWithBytes:length:encoding:。你可能想要initWithBytes:length:encoding:.

于 2014-01-06T18:31:07.770 回答
0

简而言之:您可能需要为您的 NSString 对象考虑一个合适的 const char C-string 初始值设定项。此外,在向NSString对象发送任何初始化消息之前分配内存。我希望是这样的:

char word[40];
int nChars = scanf("%39s", word);

NSString *word2 = [[NSString alloc] initWithCString:word encoding:NSASCIIStringEncoding];

请注意,每个设计的initWithCString仅支持正确为 null '\0' 终止的 8 位字符数组。对于未终止的字节数组,您可以使用initWithBytes:length:encoding:代替。

对于 Unicode 字符,您可以考虑initWithCharactersNoCopy:length:freeWhenDone:

于 2021-01-03T14:52:28.607 回答