stringWithCString deprecated... so what do i use with char* returned by sysctlbyname?
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, 开发者_如何学JAVA&size, NULL, 0);
NSString *platform = [NSString stringWithCString:machine];
free(machine);
return platform;
}
Thanks in advance!
If the C string you're using is UTF-8-encoded, then use stringWithUTF8String:
. If it's plain ASCII, then use stringWithCString:encoding:
with an encoding of NSASCIIStringEncoding
. Otherwise, it's probably encoded using Latin-1, in which case you should use stringWithCString:encoding:
with an encoding of NSISOLatin1StringEncoding
.
In this case, sysctlbyname
is almost certainly going to give you back an ASCII string, so you should do this:
NSString *platform = [NSString stringWithCString:machine encoding:NSASCIIStringEncoding];
Though using either of the other two methods will do you no harm.
You just need to specify the string encoding, which is ASCII in the case of sysctlbyname:
NSString *platform = [NSString stringWithCString:machine encoding:NSASCIIStringEncoding];
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
errorString = [NSString stringWithCString:iax_errstr];
try this
errorString = [NSString stringWithCString:iax_errstr encoding:NSASCIIStringEncoding]
精彩评论