I'm just a beginner in Cocoa developing for Snow Leopard and I have problem with editing values in data array that displayed in NSTableView
.
I tried to edit some property of my object in -tableView:setObjectValue:forTableColumn:row:
and I have EXC_BAD_ACCESS
after this.
My NSTableView
contains one column with NSButtonCell
cells and this column have identifier 'checked'.
My code is simple and looks like this:
@interface MyObj: NSObject {
BOOL checked;
}
@property (assign) BOOL checked;
@end
@imlpementation MyObj
@synthesize checked;
@end
@interface MyAppDelegate: NSObject <NSApplicationDelegate, NSTableViewDelegate, NSTableViewDataSource> {
NSMutableArray *data;
NSTableView *table;
}
@property (assign) IBOutlet NSTableView *table;
- (NSInteger) numberOfRowsInTableView:(NSTableView *)aTableView;
- (id) tableView:(NSTableView *)aTableView objectValueForTableColumn:(NSTableColumn *)aTableColumn row:(NSInteger)rowIndex;
- (void)tableView:(NSTableView *)aTableView setObjectValue:(id)anObject forTableColumn:(NSTableColumn *)aTableColumn row:(NSInteger)rowIndex;
@end
@implementation MyAppDelegate
@synthesize table;
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
data = [[NSMutableArray array] retain];
// some code that add few objects to data
// each object is instance of MyObj and I call alloc+init+retain for each
// ...
[table reloadData];
}
- (void)dealloc {
[data release];
[super dealloc];
}
- (NSInteger) numberOfRowsInTableView:(NSTableView *)aTableView {
return (data == nil ? 0 : [data count]);
}
- (id) tableView:(NSTableView *)aTableView objectValueForTableColumn:(NSTableColumn *)aTableColumn row:(NSInteger)rowIndex {
MyObj *obj;
obj = [data objectAtIndex:rowIndex];
NSString *identifier;
identifier = [aTableColumn identifier];
return [obj performSelector:NSSelectorFromString(identifier)];
}
- (void)tableView:(NSTableView *)aTableView setObjectValue:(id)anObject forTableColumn:(NSTableColumn *)aTableColumn row:(NSInteger)rowIndex {
MyObj *obj;
obj = [data objectAtIndex:rowIndex];
NSString *identifier;
identifier = [aTableColumn identifier];
if ([identifier isEqualTo:@"checked"]) {
BOOL value = [anObject boolValue];
obj.checked = value;
[data replaceObjectAtIndex:rowIndex withObject:obj];
}
[table reloadData];
}
@end
And I have raised objc_msgSend_vtable5
from -[NSButtonCell setObjectValue]
method.
I found solution for my problem. I changed BOOL checked
to NSNumber *checked
.
- (void)tableView:(NSTableView *)aTableView setObjectValue:(id)anObject forTableColumn:(NSTableColumn *)aTableColumn row:(NSInteger)rowIndex {
MyObj *obj = (MyObj *)[data objectAtIndex:rowIndex];
NSString *identifier;
identifier = [aTableColumn identifier];
if ([identifier isEqualTo:@"checked"]) {
[obj setValue:[[NSNumber numberWithBool:[anObject boolValue]] retain] forKey:[aTableColumn identifier]];
}
[table reloadData];
}
And all works fine right now. I hope it helps someone.