我收到这个错误: -[NSCFArray insertObject:atIndex:]: attempt to insert 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
Run Code Online (Sandbox Code Playgroud)
你的问题是这样的:
NSString *string = [[NSString alloc] init];
string = [textField stringValue];
[myArray addObject:string];
Run Code Online (Sandbox Code Playgroud)
首先,你有内存泄漏,因为你alloc和init一个空的NSString,但随后立即在分配失去了参照它textField的stringValue.
此外,如果textField中没有字符串,那么stringValue将返回nil并导致您的addObject:消息失败,因为您无法nil作为参数调用它.
另外,你的第一行(tableView = [[NSTableView alloc] init]; [textField stringValue];)只是没有意义.你指定你有一个IBOutlettableview,那你为什么要创建一个新的?由于您将新的tableview分配给实例变量,因此IBOutlet每次调用此方法时,您都会泄漏并重新启动tableview.此外,您正在调用stringValue并完全忽略返回值.
我建议您阅读更多关于IBOutlets如何在代码中使用它们的内容.这里有几个链接: 链接1,链接2
| 归档时间: |
|
| 查看次数: |
730 次 |
| 最近记录: |