为什么只有在使用mutableCopy时,此NSMutableAttributedString addAttribute才有效

时间:2014-05-21 21:00:15

标签: ios objective-c nsstring nsattributedstring nsmutablecopying

我有以下代码:

NSMutableAttributedString *attrS = [[NSMutableAttributedString alloc] initWithString:@"• Get Tested Son"];
NSMutableAttributedString *boldS = [[NSMutableAttributedString alloc] initWithString:@"Son"];

[boldS addAttribute:NSFontAttributeName value:SOMEBOLDFONT range:NSMakeRange(0, boldS.length)];

[attrS replaceCharactersInRange:[attrS.string rangeOfString:boldS.string]
           withAttributedString:boldS];

如您所见,我想加粗Son部分。如果我执行上述陈述,这不起作用,但只有在我这样做时才有效:

[[attrS mutableCopy] replaceCharactersInRange:[attrS.string rangeOfString:boldS.string]
                         withAttributedString:boldS];

可能是什么原因?

1 个答案:

答案 0 :(得分:3)

无论您是否addAttribute

mutableCopy都有效。您的问题基于错误的假设。因此没有答案。

运行:

NSMutableAttributedString *attrS = [[NSMutableAttributedString alloc] initWithString:@"• Get Tested Son"];
NSMutableAttributedString *boldS = [[NSMutableAttributedString alloc] initWithString:@"Son"];

UIFont *someBoldFont = [UIFont fontWithName:@"Arial" size:23.0f];
[boldS addAttribute:NSFontAttributeName value:someBoldFont range:NSMakeRange(0, boldS.length)];

NSMutableAttributedString *attrSCopy = [attrS mutableCopy];

[attrS replaceCharactersInRange:[attrS.string rangeOfString:boldS.string]
           withAttributedString:boldS];
[attrSCopy replaceCharactersInRange:[attrS.string rangeOfString:boldS.string]
           withAttributedString:boldS];

NSLog(@"%@", [attrS isEqual:attrSCopy] ? @"equal" : @"different");

它将输出equal。为replaceCharactersInRange:attrS注释掉attrSCopy,然后输出different