我收到此错误:-[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
中进行分配。
此外,如果 textField 中没有字符串,则 stringValue
将返回 nil
并导致您的 addObject:
消息失败,因为您无法使用 nil
作为参数来调用它。
此外,您的前几行 (tableView = [[NSTableView alloc] init]; [textField stringValue];
) 只是没有意义。您指定了 tableview 有一个 IBOutlet
,那么为什么要创建一个新的呢?由于您将新的表格 View 分配给实例变量,因此您会泄漏 IBOutlet,然后每次调用此方法时都会重新泄漏表格 View 。此外,您正在调用 stringValue
并完全忽略返回值。
我建议您阅读更多有关 IBOutlets
以及如何在代码中使用它们的内容。这里有几个链接:Link 1 , Link 2
关于objective-c - 我正在尝试用 Objective C 构建一个待办事项列表应用程序,但效果不佳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2672197/