从NSTextView中提取第一个非空白行的最有效方法是什么?

sam*_*sam 3 cocoa nsstring nstextview

从NSTextView中提取第一个非空白行的最有效方法是什么?

例如,如果文本是:

\n
\n
    \n
         This is the text I want     \n
 \n
Foo bar  \n
\n
Run Code Online (Sandbox Code Playgroud)

结果将是"这是我想要的文字".

这是我有的:

NSString *content = self.textView.textStorage.string;
NSInteger len = [content length];
NSInteger i = 0;

// Scan past leading whitespace and newlines
while (i < len && [[NSCharacterSet whitespaceAndNewlineCharacterSet] characterIsMember:[content characterAtIndex:i]]) {
    i++;
}
// Now, scan to first newline
while (i < len && ![[NSCharacterSet newlineCharacterSet] characterIsMember:[content characterAtIndex:i]]) {
    i++;
}
// Grab the substring up to that newline
NSString *resultWithWhitespace = [content substringToIndex:i];
// Trim leading and trailing whitespace/newlines from the substring
NSString *result = [resultWithWhitespace stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
Run Code Online (Sandbox Code Playgroud)

有更好,更有效的方式吗?

我正在考虑将它放在-textStorageDidProcessEditing:NSTextStorageDelegate方法中,以便我可以在编辑文本时获取它.这就是为什么我希望这种方法尽可能高效.

Rob*_*ger 6

只需使用NSScanner专为此类设计的产品:

NSString* output = nil;
NSScanner* scanner = [NSScanner scannerWithString:yourString];
[scanner scanCharactersFromSet:[NSCharacterSet whitespaceAndNewlineCharacterSet] intoString:NULL];
[scanner scanUpToCharactersFromSet:[NSCharacterSet newlineCharacterSet] intoString:&output];
output = [output stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
Run Code Online (Sandbox Code Playgroud)

请注意,如果您可以扫描到特定字符而不是字符集,则速度会快得多:

[scanner scanUpToString:@"\n" intoString:&output];
Run Code Online (Sandbox Code Playgroud)