You can attach a shared formatter programmatically instead of in the xib file. In your delegate method for returning the view for the cell, supposing that your cell class is MyCellView
and MyCellView
has a property theTextField
, and the view is loaded from a xib file named MyCellView.xib
:
- (NSView *)tableView:(NSTableView *)tableView viewForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row {
MyCellView *result = [tableView makeViewWithIdentifier:@"MyCellView" owner:self];
[result.theTextField setFormatter:[[self class] sharedFormatter]];
return result;
}
Then you need this sharedFormatter
method. The sharedFormatter
method will set up a lazily initialized singleton. This is a pretty common pattern in iOS and Mac OS X development, and it's a good one to learn if you haven't seen it before:
+ (NSFormatter *)sharedFormatter {
static NSFormatter *formatter;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
formatter = [[NSFormatter alloc] init];
/* Set up the formatter's attributes here */
});
return formatter;
}
So sharedFormatter
initializes its static formatter
variable at most once (the first time the sharedFormatter
method is called). The dispatch_once
causes all the code in its input block to be executed only one time, and even takes care of synchronizing calls occurring on multiple threads (though I doubt you'd be calling sharedFormatter
from multiple threads).