Swift NSAttributedString with foregroundColor crash app.

I have the next func to draw a string in a view using Core Graphics with swift 5.3 in Catalina.
Code Block
private func drawString(_ string : String, at point : CGPoint, withFont font : NSFont, andColor color : NSColor )
{
    let attributes : [NSAttributedString.Key : Any] = [NSAttributedString.Key.font : font, NSAttributedString.Key.foregroundColor : color.cgColor]
    let attStr = NSAttributedString(string:string, attributes:attributes)
attStr.draw(at:point)
}


When the app draw the string (line 8) the app crash, and in the Xcode.debug area I read:
2020-10-21 10:17:34.535356-0500 MyApp[15037:1374731] -[__NSCFType set]: unrecognized selector sent to instance 0x60000214ef80
If remove the foregroundColor att, the app runs, but the string is drawing in black.

Some Suggestion.
Thanks
Manuel C.

Answered by Claude31 in 642081022
it appears that the problem is to use cgColor.

This works for me:

Code Block
private func drawString(_ string : String, at point : CGPoint, withFont font : NSFont, andColor color : NSColor )
{
let attributes : [NSAttributedString.Key : Any] = [NSAttributedString.Key.font : font, NSAttributedString.Key.foregroundColor : color]
let attStr = NSAttributedString(string:string, attributes:attributes)
attStr.draw(at:point)
}


If you use .cgcolor, then you have to add the backgroundColor attribute to avoid crash.
But nothing draws !
Accepted Answer
it appears that the problem is to use cgColor.

This works for me:

Code Block
private func drawString(_ string : String, at point : CGPoint, withFont font : NSFont, andColor color : NSColor )
{
let attributes : [NSAttributedString.Key : Any] = [NSAttributedString.Key.font : font, NSAttributedString.Key.foregroundColor : color]
let attStr = NSAttributedString(string:string, attributes:attributes)
attStr.draw(at:point)
}


If you use .cgcolor, then you have to add the backgroundColor attribute to avoid crash.
But nothing draws !
Yes. Correct. The cuestión here is that in swift, all core graphics objects and strucks are CG(CGPoint, CGSize, CGFloat, CGColor, etc), and all drawXXXXmethos use only CG...objects, types and structs. I asume (incorrectly) that drawString... uses a CGColor, but not, it use a NSColor.

Thanks. :)
Swift NSAttributedString with foregroundColor crash app.
 
 
Q