Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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, &size, NULL, 0);
    NSString *platform = [NSString stringWithCString:machine];
    free(machine);
    return platform;
}

Thanks in advance!

like image 777
Jann Avatar asked Aug 09 '11 04:08

Jann


4 Answers

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.

like image 104
Adam Rosenfield Avatar answered Nov 14 '22 08:11

Adam Rosenfield


You just need to specify the string encoding, which is ASCII in the case of sysctlbyname:

NSString *platform = [NSString stringWithCString:machine encoding:NSASCIIStringEncoding];
like image 2
cduhn Avatar answered Nov 14 '22 10:11

cduhn


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.

like image 1
Tommy Avatar answered Nov 14 '22 09:11

Tommy


If you find error in

errorString = [NSString stringWithCString:iax_errstr];

try this

errorString = [NSString stringWithCString:iax_errstr encoding:NSASCIIStringEncoding]
like image 1
Pooja Patel Avatar answered Nov 14 '22 09:11

Pooja Patel