Objective C - 更改 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;
}];
我正在尝试遍历所有属性并向它们添加 NSUnderline 。调试时似乎 NSUnderline 被添加到字典中,但是当我第二次循环时它们被删除。 我在更新 NSDictionaries 时做错了什么吗?
[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;
}];
I am trying to loop through all attributed and add NSUnderline to them. when debugging it seems like NSUnderline is added to the dictionary, but when i loop for the second time they are removed.
Am I doing anything wrong while updating NSDictionaries?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
乔纳森的回答很好地解释了原因不起作用。为了使其工作,您需要告诉属性字符串使用这些新属性。
更改属性字符串的属性要求它是 NSMutableAttributedString。
还有一种更简单的方法可以做到这一点。 NSMutableAttributedString 定义了 addAttribute:value:range: 方法,该方法在指定范围内设置特定属性的值,而不更改其他属性。您可以通过对此方法的简单调用来替换代码(仍然需要可变字符串)。
Jonathan's answer does a good job of explaining why it doesn't work. To make it work, you need to tell the attributed string to use these new attributes.
Changing the attributes of an attributed string requires that it is a NSMutableAttributedString.
There is also an easier way to do this. NSMutableAttributedString defines the
addAttribute:value:range:
method, which sets the value of a specific attribute over the specified range, without changing other attributes. You can replace your code with a simple call to this method (still requiring a mutable string).您正在修改字典的本地副本;属性字符串没有任何方式可以看到变化。
C 中的指针是按值传递的(因此它们指向的内容是按引用传递的。)因此,当您为属性分配新值时,调用该块的代码不知道您更改了它。更改不会传播到块的范围之外。
You're modifying a local copy of the dictionary; the attributed string does not have any way to see the change.
Pointers in C are passed by value (and thus what they point to is passed by reference.) So when you assign a new value to
attributes
, the code that called the block has no idea you changed it. The change does not propagate outside of the block's scope.