Question

I try to use a CATextLayer together with a NSMutableAttributedString.

Once I set the string property of my CATextLayer to an NSMutableAttributedString it gets automatically replaced by an immutable NSAttributedString.

I checked for the result of calling class on the string property before and after setting it and the pointer. I hand an NSConcreteMutableAttributedString to the CoreTextLayer and right after the setter is called and I ask the CATextLayer for the class of its string property, I get this result: NSConcreteAttributedString. Also the pointers are different before and after (obviously).

What can I do to get that right?

Was it helpful?

Solution

There's nothing wrong with what's happening, so there's nothing to "get right". Just look at the documentation! The string property is declared like this:

@property(copy) id string

That means exactly what you're seeing: when you set it, it takes an immutable copy. This is deliberate: if it were not so, then the string could be mutated behind the layer's back, which would throw everything off. Indeed, if your own classes have any string properties, they should work the same way.

If you need to change the string, just set the string property again. If you need to change the string based on its current value, fetch the string, make a mutableCopy, change it, and set it - just as with any of the immutable / mutable class cluster pairs in Foundation.

The name of the class is irrelevant, as I presume you realize: it's a class cluster, so private names like NSConcreteMutableAttributedString (instead of NSMutableString) are none of your business. You should never use the class name as a way of testing whether a mutable Foundation class instance is mutable, in any case: just ask the object whether it responds to a mutable method.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top