Enumerate NSString characters via pointer

cocoa-touch, ios, objective-c, string

Solution

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.

Problem

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; ```

Original source