Convert int to CFString without CFStringCreateWith

2019-08-24 01:43发布

The following is extremely slow for what I need.

CFStringCreateWithFormat(NULL, NULL, CFSTR("%d"), i);

Currently this takes 20,000ns in my tests to execute on my 3gs. Perhaps that sounds fast, but I can create and release two NSMutableDictionaries in the time this executes. My C is weak, but there must be something equivalent to itoa that I can use on IOS.

1条回答
仙女界的扛把子
2楼-- · 2019-08-24 02:05

This is the faster I can get:

CFStringRef TECFStringCreateWithInteger(NSInteger integer)
{
    size_t size = 21; // long enough for 64 bits integer
    char buffer[size];
    char *characters = buffer + size;

    *(--characters) = 0; // NULL-terminated string
    int sign = integer < 0 ? -1 : 1;

    do {
        *(--characters) = '0' + (integer % 10) * sign;
        integer /= 10;
    }
    while ( integer );

    if ( sign == -1 )
        *(--characters) = '-';

    return CFStringCreateWithCString(NULL, characters, kCFStringEncodingASCII);
}
查看更多
登录 后发表回答