iosobjective-cnsstringnsattributedstringnsmutablecopying

Why does this NSMutableAttributedString addAttribute work only if I use a mutableCopy


I have the following code :

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

As you can see, I want to bold the Son part. This does not work if I do the above statements but only works if I do :

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

What might be the reason for that?


Solution

  • addAttribute works regardless of whether you take a mutableCopy. Your question is based on a false assumption. It therefore has no answer.

    Run this:

    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");
    

    It will output equal. Comment out the replaceCharactersInRange: for either attrS or attrSCopy and it will output different.