Search code examples
iosobjective-cnsattributedstring

What is the content of character attributes like NSFontAttributeName?


I was reading the apple documentation to learn how to format text for iOS. I came across an attributed string and most of it made sense to me. However, while looking up the different kinds of attributes, I saw that they are all declared as NSString. For example:

NSString *const NSFontAttributeName;
NSString *const NSParagraphStyleAttributeName;
...
...

We pass in these string objects in a dictionary with the value being that particular attribute (e.g., a UIFont object). However, what I do not understand is what the content of that string has to do with the attribute itself. Do they just contain the name of the attribute? (i.e NSFontAttributeName might contain a string like @"NSFontAttribute")

Surely there must be a reason why has apple to chosen to do it this way?

Edit: My question isn't about why they use a string object as a key to the dictionary but why they use a predefined constant string object named NSFontAttributeName instead of allowing us to manually pass in a string @"NSFontAttribute" as the key. That's why I wondered whether the contents of their predefined string object has anything to do with this.


Solution

  • In this case, Apple uses an NSDictionary to contain an arbitrary set of key/value pairs. Doing it this way means you have a lot of flexibility because you can have no attributes, one attribute, or two dozen attributes with the same programming interface. And if in two years time there are attributes available that you haven't even thought about, Apple doesn't have to introduce any new APIs to support you setting these attributes.

    The reason for using a constant instead of a string literal is that the compiler can save you if you misspell a name. If you wrote @"NSFontattribute" instead of @"NSFontAttribute", the compiler wouldn't know that you got it wrong.