Objective C - 更改NSAttributedString中的所有属性?

ary*_*axt 9 iphone objective-c nsdictionary nsattributedstring

[attributedString enumerateAttributesInRange:range options:NSAttributedStringEnumerationReverse usingBlock:
     ^(NSDictionary *attributes, NSRange range, BOOL *stop) {

         NSMutableDictionary *mutableAttributes = [NSMutableDictionary dictionaryWithDictionary:attributes];
         [mutableAttributes setObject:[NSNumber numberWithInt:1] forKey:@"NSUnderline"];
         attributes = mutableAttributes;

     }];
Run Code Online (Sandbox Code Playgroud)

我试图循环所有属性并添加NSUnderline给他们.在调试时,似乎NSUnderline被添加到字典中,但是当我第二次循环时它们被删除.我在更新NSDictionaries时做错了什么?

ugh*_*fhw 20

Jonathan的回答很好地解释了为什么它不起作用.要使其工作,您需要告诉属性字符串使用这些新属性.

[attributedString enumerateAttributesInRange:range options:NSAttributedStringEnumerationReverse usingBlock:
     ^(NSDictionary *attributes, NSRange range, BOOL *stop) {

         NSMutableDictionary *mutableAttributes = [NSMutableDictionary dictionaryWithDictionary:attributes];
         [mutableAttributes setObject:[NSNumber numberWithInt:1] forKey:@"NSUnderline"];
         [attributedString setAttributes:mutableAttributes range:range];

 }];
Run Code Online (Sandbox Code Playgroud)

更改属性字符串的属性要求它是NSMutableAttributedString.

还有一种更简单的方法可以做到这一点.NSMutableAttributedString定义addAttribute:value:range:方法,该方法在指定范围内设置特定属性的值,而不更改其他属性.您可以通过对此方法的简单调用来替换您的代码(仍然需要可变字符串).

[attributedString addAttribute:@"NSUnderline" value:[NSNumber numberWithInt:1] range:(NSRange){0,[attributedString length]}];
Run Code Online (Sandbox Code Playgroud)


Jon*_*pan 5

你正在修改字典的本地副本; 属性字符串无法查看更改.

C中的指针按值传递(因此它们指向的是通过引用传递的.)因此,当您为其分配新值时attributes,调用该块的代码无法更改它.更改不会传播到块的范围之外.