I’m getting this error: -[NSCFArray insertObject:atIndex:]: attempt to insert nil
Here is the .m file:
/*
IBOutlet NSTextField *textField;
IBOutlet NSTabView *tableView;
IBOutlet NSButton *button;
NSMutableArray *myArray;
*/
#import "AppController.h"
@implementation AppController
-(IBAction)addNewItem:(id)sender
{
myArray = [[NSMutableArray alloc]init];
tableView = [[NSTableView alloc] init];
[tableView setDataSource:self];
[textField stringValue];
NSString *string = [[NSString alloc] init];
string = [textField stringValue];
[myArray addObject:string];
NSLog(@"%d",[myArray count]);
NSLog(@"%@",string);
}
- (int)numberOfRowsInTableView:(NSTableView *)aTableView
{
return [myArray count];
}
- (id)tableView:(NSTableView *)aTableView
objectValueForTableColumn:(NSTableColumn *)aTableColumn
row:(int)rowIndex
{
//NSString *data = [myArray objectAtIndex:rowIndex];
return [myArray objectAtIndex:rowIndex];
}
@end
Your problem is this:
First off, you have a memory leak, since you
allocandinitan emptyNSString, but then immediately lose the reference to it by assigning in thetextField‘sstringValue.Also, if the textField doesn’t have a string in it, then
stringValuewill returnniland cause youraddObject:message to fail, since you can’t invoke it withnilas a parameter.In addition, your first couple lines (
tableView = [[NSTableView alloc] init]; [textField stringValue];) just don’t make sense. You specified that you have anIBOutletto the tableview, so why are you creating a new one? Since you’re assigning the new tableview into your instance variable, you’re leaking theIBOutletand then releaking a tableview every time this method is invoked. Also, you’re invokingstringValueand totally ignoring the return value.I recommend reading up a bit more about
IBOutletsand how to use them in your code. Here are a couple links: Link 1, Link 2