Binding CoreData Managed Object to NSTextFieldCell subclass
Posted
by ndg
on Stack Overflow
See other posts from Stack Overflow
or by ndg
Published on 2010-05-20T13:06:34Z
Indexed on
2010/05/20
15:40 UTC
Read the original article
Hit count: 352
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 falls down when editing multiple rows. The behaviour I'm seeing is that editing a row will work as expected until you try to edit another row. Upon editing another row, all previously edited rows will have their "desc" value set to the value of the currently selected row.
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.
© Stack Overflow or respective owner