2011-07-21 7 views
9
[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がディクショナリに追加されたようにデバッグすると思われますが、2回目にループすると削除されます。 NSDictionariesの更新中に何か間違っていますか?目的C - NSAttributedStringのすべての属性を変更しますか?

答えて

20

Jonathan's answerなぜそれがうまくいかないのか説明するのは良い仕事です。動作させるには、これらの新しい属性を使用するように属性付き文字列に指示する必要があります。

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

}]; 

属性付き文字列の属性を変更するには、それがNSMutableAttributedStringである必要があります。

これを行う簡単な方法もあります。 NSMutableAttributedStringは、addAttribute:value:range:メソッドを定義します。これは、指定された範囲の特定の属性の値を、他の属性を変更することなく設定します。このメソッドの簡単な呼び出しでコードを置き換えることができます(変更可能な文字列が必要です)。

[attributedString addAttribute:@"NSUnderline" value:[NSNumber numberWithInt:1] range:(NSRange){0,[attributedString length]}]; 
+0

あなたはattributedStringに関する私の他の質問を見ることができますか?ありがとうございます:http://stackoverflow.com/questions/6783754/objective-c-nsattributedstring-extend-attributes – aryaxt

+0

'addAttribute:value:range:'同じ値を持つ既存の値を同じ範囲で上書きしますか?それとも、属性を追加しないだけですか? – chown

+0

@chownドキュメンテーションは言いませんので、私はそれをテストし、既存の値を上書きすることを確認します。 – ughoavgfhw

6

辞書のローカルコピーを変更しています。属性付き文字列には変更が反映されません。

Cのポインタは値によって渡されます(したがって、ポインタは参照によって渡されます)。attributesに新しい値を代入すると、ブロックを呼び出したコードは変更したことがわかりません。変更はブロックのスコープの外部に伝播しません。

+0

解決策は何ですか? – aryaxt

+0

なぜdownvote? –

関連する問題