I have an NSTableView which has its first column set to contain a custom NSTextFieldCell. My custom NSTextFieldCell needs to allow the user to edit a "desc" property within my Managed Object but to also display an "info" string that it contains (which is not editable). To achieve this, I followed this tutorial. In a nutshell, the tutorial suggests editing your Managed Objects generated subclass to create and pass a dictionary of its contents to your NSTableColumn via bindings.
This works well for read-only NSCell implementations, but I'm looking to subclass NSTextFieldCell to allow the user to edit the "desc" property of my Managed Object. To do this, I followed one of the articles comments, which suggests subclassing NSFormatter to explicitly state which Managed Object property you would like the NSTextFieldCell to edit. Here's the suggested implementation:
@implementation TRTableDescFormatter
- (BOOL)getObjectValue:(id *)anObject forString:(NSString *)string errorDescription:(NSString **)error
{
if (anObject != nil){
*anObject = [NSDictionary dictionaryWithObject:string forKey:@"desc"];
return YES;
}
return NO;
}
- (NSString *)stringForObjectValue:(id)anObject
{
if (![anObject isKindOfClass:[NSDictionary class]]) return nil;
return [anObject valueForKey:@"desc"];
}
- (NSAttributedString*)attributedStringForObjectValue:(id)anObject withDefaultAttributes:(NSDictionary *)attrs
{
if (![anObject isKindOfClass:[NSDictionary class]]) return nil;
NSAttributedString *anAttributedString = [[NSAttributedString alloc] initWithString: [anObject valueForKey:@"desc"]];
return anAttributedString;
}
@end
I assign the NSFormatter subclass to my cell in my NSTextFieldCell subclass, like so:
- (void)awakeFromNib
{
TRTableDescFormatter *formatter = [[[TRTableDescFormatter alloc] init] autorelease];
[self setFormatter:formatter];
}
This seems to work, but is extremely patch. On occasion, clicking to edit a row will cause its value to nullify. On other occasions, the value you enter on one row will populate other rows within the table.
I've been doing a lot of reading on this subject and would really like to get to the bottom of this. What's more frustrating is that my NSTextFieldCell is rendering exactly how I would like it to. This editing issue is my last obstacle! If anyone can help, that would be greatly appreciated.