Alastair’s Place

Software development, Cocoa, Objective-C, life. Stuff like that.

NSCell and Overriding -objectValue

It’s sometimes tempting when writing a cell class to override the -objectValue and -setObjectValue: methods of NSCell and let something other than the cell store the value (perhaps you could even generate the value from some other data).

But please don’t.

The problem is that NSCell doesn’t use the -objectValue accessor in some important cases1, which means that if you override -objectValue, some of the cell’s methods will produce inconsistent results.

The right way to use NSCell is to always let NSCell store the data, which will avoid significant pain if someone is trying to do something fancy in a subclass of your cell.

1 For instance, in the private _stringForEditing and _attributedStringForEditing methods, which are used to get the string to put into the field editor if you’re using NSCell’s text editing support. Arguably the fault here lies with NSCell, but either way, there are no problems if you let NSCell store its own data.