Objective c I';I’我正试图在Objective C中构建一个待办事项列表应用程序,但遇到了一些问题
我收到以下错误:Objective c I';I’我正试图在Objective C中构建一个待办事项列表应用程序,但遇到了一些问题,objective-c,cocoa,Objective C,Cocoa,我收到以下错误:-[NSCFArray insertObject:atIndex:]:尝试插入nil 以下是.m文件: /* IBOutlet NSTextField *textField; IBOutlet NSTabView *tableView; IBOutlet NSButton *button; NSMutableArray *myArray; */ #import "AppController.h" @implementation AppController -(
-[NSCFArray insertObject:atIndex:]:尝试插入nil
以下是.m文件:
/*
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
你的问题是:
NSString *string = [[NSString alloc] init];
string = [textField stringValue];
[myArray addObject:string];
首先,您有一个内存泄漏,因为您alloc
和init
一个空的NSString
,但是通过在textField
的stringValue
中赋值,会立即丢失对它的引用
此外,如果文本字段中没有字符串,则stringValue
将返回nil
,并导致addObject:
消息失败,因为您不能将nil
作为参数调用它
此外,您的前几行(tableView=[[NSTableView alloc]init];[textField stringValue];
)根本没有意义。您指定在tableview中有一个IBOutlet
,那么为什么要创建一个新的呢?由于将新的tableview分配到实例变量中,因此会泄漏IBOutlet
,然后在每次调用此方法时重新生成tableview。此外,您正在调用stringValue
并完全忽略返回值
我建议您多读一点关于IBOutlets
,以及如何在代码中使用它们。这里有几个链接:,您的问题是:
NSString *string = [[NSString alloc] init];
string = [textField stringValue];
[myArray addObject:string];
首先,您有一个内存泄漏,因为您alloc
和init
一个空的NSString
,但是通过在textField
的stringValue
中赋值,会立即丢失对它的引用
此外,如果文本字段中没有字符串,则stringValue
将返回nil
,并导致addObject:
消息失败,因为您不能将nil
作为参数调用它
此外,您的前几行(tableView=[[NSTableView alloc]init];[textField stringValue];
)根本没有意义。您指定在tableview中有一个IBOutlet
,那么为什么要创建一个新的呢?由于将新的tableview分配到实例变量中,因此会泄漏IBOutlet
,然后在每次调用此方法时重新生成tableview。此外,您正在调用stringValue
并完全忽略返回值
我建议您多读一点关于IBOutlets
,以及如何在代码中使用它们。这里有几个链接: