stringWithCString 已弃用...那么我该如何使用 sysctlbyname 返回的 char* 呢?
我知道在 SQLite 中更改 stringWithCString
时如何处理这个问题...您只需使用 stringWithUTF8String
即可。当 sysctlbyname
返回时,这与 char *
相同吗? (见下面的代码)
- (NSString *) platform{
size_t size;
sysctlbyname("hw.machine", NULL, &size, NULL, 0);
char *machine = malloc(size);
sysctlbyname("hw.machine", machine, &size, NULL, 0);
NSString *platform = [NSString stringWithCString:machine];
free(machine);
return platform;
}
提前致谢!
I know how to handle this when changing stringWithCString
in SQLite... you just stringWithUTF8String
instead. Is this the same with a char *
when it is returned by sysctlbyname
? (see code below)
- (NSString *) platform{
size_t size;
sysctlbyname("hw.machine", NULL, &size, NULL, 0);
char *machine = malloc(size);
sysctlbyname("hw.machine", machine, &size, NULL, 0);
NSString *platform = [NSString stringWithCString:machine];
free(machine);
return platform;
}
Thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您使用的 C 字符串是 UTF-8 编码的,则使用
stringWithUTF8String:
。如果它是纯 ASCII,则使用stringWithCString:encoding:
和NSASCIIStringEncoding
编码。否则,它可能使用 Latin-1 进行编码,在这种情况下,您应该使用stringWithCString:encoding:
以及NSISOLatin1StringEncoding
编码。在这种情况下,
sysctlbyname
几乎肯定会返回一个 ASCII 字符串,因此您应该这样做:尽管使用其他两种方法之一不会对您造成任何损害。
If the C string you're using is UTF-8-encoded, then use
stringWithUTF8String:
. If it's plain ASCII, then usestringWithCString:encoding:
with an encoding ofNSASCIIStringEncoding
. Otherwise, it's probably encoded using Latin-1, in which case you should usestringWithCString:encoding:
with an encoding ofNSISOLatin1StringEncoding
.In this case,
sysctlbyname
is almost certainly going to give you back an ASCII string, so you should do this:Though using either of the other two methods will do you no harm.
您只需要指定字符串编码,在 sysctlbyname 的情况下为 ASCII:
You just need to specify the string encoding, which is ASCII in the case of sysctlbyname:
stringWithCString: 已弃用,取而代之的是 stringWithCString:encoding:。您可以使用 [NSString defaultCStringEncoding] 来准确重现 stringWithCString: 的行为:但您最好指定 NSASCIIStringEncoding 或 NSUTF8StringEncoding。 sysctlbyname 返回的编码似乎是隐式的,因此 7 位 ASCII 是一个安全的选择,使得任一编码都适合。
stringWithCString: is deprecated in favour of stringWithCString:encoding:. You could use [NSString defaultCStringEncoding] to exactly reproduce the behaviour of stringWithCString: but you're probably better off specifying NSASCIIStringEncoding or NSUTF8StringEncoding. The encoding returned by sysctlbyname seems to be implicit, so 7-bit ASCII is a safe bet, making either encoding suitable.
如果您发现错误,
请尝试此操作
If you find error in
try this