Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enumerate NSString characters via pointer

How can I enumerate NSString by pulling each unichar out of it? I can use characterAtIndex but that is slower than doing it by an incrementing unichar*. I didn't see anything in Apple's documentation that didn't require copying the string into a second buffer.

Something like this would be ideal:

for (unichar c in string) { ... }

or

unichar* ptr = (unichar*)string;
like image 216
jjxtra Avatar asked Apr 17 '12 20:04

jjxtra


1 Answers

You can speed up -characterAtIndex: by converting it to it's IMP form first:

NSString *str = @"This is a test";

NSUInteger len = [str length]; // only calling [str length] once speeds up the process as well
SEL sel = @selector(characterAtIndex:);

// using typeof to save my fingers from typing more
unichar (*charAtIdx)(id, SEL, NSUInteger) = (typeof(charAtIdx)) [str methodForSelector:sel];

for (int i = 0; i < len; i++) {
    unichar c = charAtIdx(str, sel, i);
    // do something with C
    NSLog(@"%C", c);
}  

EDIT: It appears that the CFString Reference contains the following method:

const UniChar *CFStringGetCharactersPtr(CFStringRef theString);

This means you can do the following:

const unichar *chars = CFStringGetCharactersPtr((__bridge CFStringRef) theString);

while (*chars)
{
    // do something with *chars
    chars++;
}

If you don't want to allocate memory for coping the buffer, this is the way to go.

like image 60
Richard J. Ross III Avatar answered Sep 28 '22 15:09

Richard J. Ross III