I’m using the following code to make selected text bold in an NSTextView
[self.textView.attributedString addAttribute:NSFontAttributeName value:[NSFont boldSystemFontOfSize:12] range:self.textView.selectedRange];
Where self.textView is an outlet to an NSTextView . Xcode gives a warning that addAttribute may not work as the property is of type NSAttributedString and not NSMutableAttributedString.The code works but is it wrong to do it this way ? If so what is the proper way ?
UPDATE :
I found another way of doing this :
NSMutableAttributedString *textFieldText = [self.textView.attributedString mutableCopy];
[textFieldText addAttribute:NSFontAttributeName value:[NSFont boldSystemFontOfSize:12] range:self.textView.selectedRange];
[self.textView.textStorage setAttributedString:textFieldText];
Since both methods work , I’d like to know which is better.
General Remarks
Take the interface that a class exposes at its word. It is not best practice to assume that the return type is a specific subclass of the declared return type.
This is especially important in the context of a class cluster: different implementations of the common interface may have different different return types for the same method though those return types are guaranteed to be compatible with the type declared in the header.
Supposing you could be guaranteed that all undocumented subclasses in the class cluster presently return the same specific subclass of the type declared in the header, you cannot be guaranteed that that will remain the case in future revisions of Apple’s frameworks.
NSTextView
The question is about an
NSTextView‘s and its propertytextStorage. This property is of typeNSTextStorage, a “semiconcrete subclass ofNSMutableAttributedString“. The documentation goes on, describing the preferred mechanism for changing the string stored by theNSTextStorageor its attributes:NSTextViewexposes its propertytextStoragewhich is an instance ofNSTextStorage.NSTextStorageis a subclass ofNSMutableAttributedString. Consequently, we can simply add our attribute to it: