objective-c - 通过指针枚举 NSString 字符

标签 objective-c ios string cocoa-touch

如何通过提取每个 unichar 来枚举 NSString?我可以使用 characterAtIndex,但这比使用递增的 unichar* 慢。我在 Apple 的文档中没有看到任何不需要将字符串复制到第二个缓冲区的内容。

像这样的东西是理想的:

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

unichar* ptr = (unichar*)string;

最佳答案

您可以通过先将 -characterAtIndex: 转换为 IMP 形式来加快速度:

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);
}  

编辑:看来 CFString Reference包含以下方法:

const UniChar *CFStringGetCharactersPtr(CFStringRef theString);

这意味着您可以执行以下操作:

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

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

如果您不想分配内存来处理缓冲区,这是可行的方法。

关于objective-c - 通过指针枚举 NSString 字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10198913/

相关文章:

iphone - 如何从 Core Data 中获取没有任何符合一组条件的亲戚的对象?

ios - NSNumberFormatter:用 AND 助词拼出一个数字(英式拼写)

ios - AVAudioRecorder/AVAudioSession 与 Apple Airpods

ios - 在 RxSwift 的 UICollectionViewCell 中订阅 UIButton 点击​​?

iOS Firebase - 如何从不同节点中删除具有相同 key 的子节点

ios - 如何使用 iPhone 连接到服务器(无浏览器)

ios - Xcode 6-基础国际化-导出和导入en.xliff文件

c - strcpy () 无法正常工作

r - R:如何将数据帧值缩短为第一个字符

java - 如何循环遍历字符串然后查找该字符串的一部分是否在 arrayList 中