NSLinguisticTagger - enumerateLinguisticTagsInRange块不限制范围

时间:2013-03-19 04:15:35

标签: ios objective-c xcode objective-c-blocks

我在类似的方法中使用enumerateLinguisticTagsInRange

[nonAttributedString enumerateLinguisticTagsInRange:stringRange
                                           scheme:NSLinguisticTagSchemeTokenType
                                          options:NSLinguisticTaggerOmitWhitespace | NSLinguisticTaggerOmitPunctuation | NSLinguisticTaggerJoinNames
                                      orthography:[NSOrthography orthographyWithDominantScript:@"Latn" languageMap:languageMap]
                                       usingBlock:^(NSString *tag, NSRange tokenRange, NSRange sentenceRange, BOOL *stop) {

       // If the token is a word...
       if ([tag isEqualToString:@"Word"])
       {
           // (And add to the tracking dictionary)
           NSMutableDictionary *wordAndRange = [[NSMutableDictionary alloc] init];
           [wordAndRange setObject:[NSNumber numberWithInt:(tokenRange.location + tokenRange.length)] forKey:[nonAttributedString substringWithRange:tokenRange]];

           [typedWordsAndRanges addObject:wordAndRange];
       }
   }];

标记器工作正常,但不会将范围限制为stringRange。它通过nonAttributedString完整地枚举。

如果我在此块上方包含以下日志:

 NSLog(@"########### stringRange.location = %d", stringRange.location);
 NSLog(@"########### stringRange.length = %d", stringRange.length);
 NSLog(@"########### substring = %@", [nonAttributedString substringWithRange:stringRange]);

我得到以下输出:

2013-03-18 21:06:27.744 WEJ[13231:c07] ########### stringRange.location = 10
2013-03-18 21:06:27.745 WEJ[13231:c07] ########### stringRange.length = 4
2013-03-18 21:06:27.805 WEJ[13231:c07] ########### substring =  de 

所以stringRange是正确的。但是,它仍在整个nonAttributedString中进行枚举。

我做错了什么?

1 个答案:

答案 0 :(得分:0)

docs for enumerateTagsInRange:scheme:options:usingBlock:州:

  

重要的是要注意,此方法将返回与给定范围相交的所有标记的范围。

如果您只想考虑stringRange完全的那些令牌,则必须在调用nonAttributedString之前从enumerateTagsInRange::::检索该子字符串。