【问题标题】:Why does this NSMutableAttributedString addAttribute work only if I use a mutableCopy为什么这个 NSMutableAttributedString addAttribute 只有在我使用 mutableCopy 时才有效
【发布时间】:2014-05-21 21:00:15
【问题描述】:

我有以下代码:

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

这可能是什么原因?

【问题讨论】:

  • 怎么不行?你在哪里打电话给addAttribute
  • 我看不出你在哪里加粗NSMutableAttributedString:你所做的就是为同一个字符串更改一个字符串。有没有 addAttributes 或类似的东西你忘了在这里发帖?
  • 我无法复制这个。这是您运行并遇到问题的真实代码吗?
  • 和 Chuck 一样,我运行了这段代码,它运行良好。你在别处犯了一个错误。
  • 直观地说,mutableCopy 创建了一个接收者的副本——也就是说,一个与接收者具有相同属性的新对象——它是可变的。

标签: ios objective-c nsstring nsattributedstring nsmutablecopying


【解决方案1】:

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。注释掉attrSattrSCopyreplaceCharactersInRange:,它将输出different

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-18
    • 2015-05-26
    • 2016-12-12
    • 2016-07-09
    • 2011-11-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多