0

这NSMutableAttributedString的addAttribute工作,我有以下代码:为什么只有当我使用mutableCopy

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]; 

什么可能是其中的原因:如果我做上述表述的,但只有工作,如果我这样做不行?

+2

它不起作用?你在哪里调用'addAttribute'? –

+1

我没有看到你粗体的地方'NSMutableAttributedString':你所做的就是改变同一个字符串的字符串。有没有'addAttributes'或类似的东西,你忘了在这里发布? – Emilie

+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:注释为attrSattrSCopy,它将输出different

相关问题