NSStringFromRect

While teaching myself how to program Cocoa (can you smell the delicious?) via Aaron Hillegass’s Cocoa Programming for Mac OS X, I ran into some difficulties with a challenge he gives in the book. This particular challenge occurs, for those following along, in chapter 15 “Images and Mouse Events.” He would like us to create an application using NSBezierPath in a custom NSView to draw ovals on the screen.

I have a faulty implementation. It works but damn is it a hack. I don’t know how much memory it leaks. I don’t know how efficient it runs. I don’t know if it follows the proper idioms for Mac programming. It works. Let’s leave it at that.

Yet, I would like to clean it up and make it a simple demo program (save, delete, undos, etc.). One issue is the use of document based application for the base. I don’t think I am following the Model-View-Controller paradigm. I have the view doing all the work. I would like to separate that by having the MyDocument class save and manage the NSRects in an NSMutableArray. Yet the NSArray holds objects and NSRect is a struct. What to do?

This article perfectly describes a solution to my problem. It is also well written. Damn. Programming for the Mac is fun.

Once you become accustomed to NSLogging everything under the sun, it can come as quite a surprise that a few common Objective-C types don’t bend so easily as the rest. Examples of such types are NSRect, NSSize, and NSRange. These compromised “objects” are implemented as plain C-structs rather than as proper objects, presumably as a performance consideration. Since they’re not objects, there is no freebie “description” method enabling them to be effortlessly passed as arguments to NSLog.

It also turns out I could’ve used NSValue. That is beautiful.

Posted by broderic

Yo! I'm the writer here. Super sauce.

One Reply to “NSStringFromRect”

  1. Hi there – thanks for linking to my entry. I am glad you picked up on the “NSValue” followup that played out in the comments. You will definitely find occasion to simply use the “StringFromBlah” methods but I myself had my eyes opened to the extreme usefulness of NSValue by the dialogue that ensued after I wrote that entry.

    Daniel Jalkut

Comments are closed.