iPhone - 用我的TextView替换换行符?

时间:2011-07-12 05:18:06

标签: iphone objective-c line-breaks

我正在尝试将lineBreaks中的UITextView转换为<br />标记, 为什么以下线路崩溃?它抱怨[NSCharacterSet newlineCharacterSet],因为当我传递一个正常的字符串时,它可以正常工作

[myMutableString stringByReplacingOccurrencesOfString:
  [NSCharacterSet newlineCharacterSet] withString:@"<br />"];

Terminating app due to uncaught exception 'NSInvalidArgumentException', 
reason: '-[__NSCFCharacterSet length]: unrecognized selector sent to 
instance 0x7b1cc80'

1 个答案:

答案 0 :(得分:4)

NSCharacterSet不是NSString。所以你传递了错误的论点。 如果您只有换行符“\ n”,则可以使用:

[myMutableString stringByReplacingOccurrencesOfString:@"\n" 
                                           withString:@"<br />"];

如果您还有“\ r”和“\ lf”,您可以尝试这样的事情(未经测试)

NSRange range;
while((range = [myMutableString rangeOfCharacterFromSet:
                [NSCharacterSet newlineCharcaterSet]]).location != NSNotFound) {
    [myMutableString replaceCharactersInRange:range withString:@"<br />"];
}