views:

64

answers:

1

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
+5  A: 

Your problem is this:

NSString *string = [[NSString alloc] init];
string = [textField stringValue];
[myArray addObject:string];

First off, you have a memory leak, since you alloc and init an empty NSString, but then immediately lose the reference to it by assigning in the textField's stringValue.

Also, if the textField doesn't have a string in it, then stringValue will return nil and cause your addObject: message to fail, since you can't invoke it with nil as a parameter.

In addition, your first couple lines (tableView = [[NSTableView alloc] init]; [textField stringValue];) just don't make sense. You specified that you have an IBOutlet to the tableview, so why are you creating a new one? Since you're assigning the new tableview into your instance variable, you're leaking the IBOutlet and then releaking a tableview every time this method is invoked. Also, you're invoking stringValue and totally ignoring the return value.

I recommend reading up a bit more about IBOutlets and how to use them in your code. Here are a couple links: Link 1, Link 2

Dave DeLong