NSString不会覆盖新值

时间:2013-10-02 16:03:43

标签: objective-c nsstring ios7

尝试从文本中删除所有网址:

- (NSString *)cleanText:(NSString *)text{
    NSString *string = @"This is a sample of a http://abc.com/efg.php?EFAei687e3EsA sentence with a URL within it.";
    NSDataDetector *linkDetector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink error:nil];
    NSArray *matches = [linkDetector matchesInString:string options:0 range:NSMakeRange(0, [string length])];

    for (NSTextCheckingResult *match in matches) {
        if ([match resultType] == NSTextCheckingTypeLink) {
            NSString *matchingString = [match description];
            NSLog(@"found URL: %@", matchingString);
            string = [string stringByReplacingOccurrencesOfString:matchingString withString:@""];
        }
    }
    NSLog(string);
    return string;
}

但是string返回不变(匹配)。

更新。:控制台输出:

found URL: <NSLinkCheckingResult: 0xb2b03f0>{22, 36}{http://abc.com/efg.php?EFAei687e3EsA}
2013-10-02 20:19:52.772 
This is a sample of a http://abc.com/efg.php?EFAei687e3EsA sentence with a URL within it and a number 097843.

由@Raphael Schweikert完成的工作配方。

2 个答案:

答案 0 :(得分:2)

问题是[match description]没有返回匹配的字符串;它返回一个如下所示的字符串:

"<NSLinkCheckingResult: 0x8cd5150>{22,36}{http://abc.com/efg.php?EFAei687e3EsA}"

要替换字符串中匹配的网址,您应该执行以下操作:

string = [string stringByReplacingCharactersInRange:match.range withString:@""];

答案 1 :(得分:1)

根据Apple’s own Douglas Davidson,匹配保证按照它们在字符串中出现的顺序排列。因此,不是对matches数组进行排序(如I suggested),而是可以反向迭代。

整个代码示例如下所示:

NSString *string = @"This is a sample of a http://abc.com/efg.php sentence (http://abc.com/efg.php) with a URL within it and some more text afterwards so there is no index error.";
NSDataDetector *linkDetector = [NSDataDetector dataDetectorWithTypes:0|NSTextCheckingTypeLink error:nil];
NSArray *matches = [linkDetector matchesInString:string options:0 range:NSMakeRange(0, [string length])];
for (NSTextCheckingResult *match in [matches reverseObjectEnumerator]) {
    string = [string stringByReplacingCharactersInRange:match.range withString:@""];
}

match.resultType == NSTextCheckingTypeLink的检查可以省略,因为您已经在您只对链接感兴趣的选项中指定了。