使用NSMutableArray与NSTableView(Cocoa)时遇到问题

时间:2011-01-10 09:17:25

标签: objective-c macos nsmutablearray nstableview

我在尝试在简单的ToDo列表应用程序中使用带有NSTableView控制器的NSMutableArray时遇到问题。添加项目不起作用,尝试删除项目会给我一个错误-[NSCFArray removeObjectAtIndex:]: index (0) beyond bounds (0)。我似乎无法找到我的问题的原因,因为尝试添加项目不会返回任何错误,并且删除一个错误导致没有明显的解决方案。我的代码如下:

AppController.h

//
//  AppController.h
//  ToDo
//
//  Created by Rhys Powell on 10/01/11.
//

#import <Cocoa/Cocoa.h>
#import <BWToolkitFramework/BWToolkitFramework.h>

@interface AppController : NSObject {
    IBOutlet BWAnchoredButton *addButton;
    IBOutlet BWAnchoredButton *removeButton;
    IBOutlet NSMenuItem *clearAll;
    IBOutlet NSTableView *tableView;
    NSMutableArray *toDoList;
}
- (IBAction)addToDo:(id)sender;
- (IBAction)removeToDo:(id)sender;
- (IBAction)clearAllToDos:(id)sender;
@end

AppController.m

//
//  AppController.m
//  ToDo
//
//  Created by Rhys Powell on 10/01/11.
//

#import "AppController.h"


@implementation AppController

- (id)init
{
    [super init];

    NSLog(@"Initialising...");

    toDoList = [[NSMutableArray arrayWithObject:@"Add a ToDo with the '+' button"] retain];

    return self;
}

- (IBAction)addToDo:(id)sender
{
    NSLog(@"Added a ToDo");
    [toDoList addObject:@"Test"];
}

- (IBAction)removeToDo:(id)sender
{
    [toDoList removeObjectAtIndex:[tableView selectedRow]];
}

- (IBAction)clearAllToDos:(id)sender
{
    [toDoList removeAllObjects];
}

- (int)numberOfRowsInTableView:(NSTableView *)tv
{
    return [toDoList count];
}

- (id)tableView:(NSTableView *)tv objectValueForTableColumn:(NSTableColumn *)tableColumn row:(int)row
{
    return [toDoList objectAtIndex:row];
}

@end

我还应该注意,初始字符串我使用显示初始化数组,但我无法删除它或添加新字符串。

3 个答案:

答案 0 :(得分:3)

不确定底层问题,但我看到的第一件事是你从基础数组中删除/添加行,但没有告诉表格。请务必在[tableView reloadData]addToDoremoveToDo内致电clearAllToDos

[NSMutableArray arrayWithObject;...]电话很好,因为您随后也会拨打retain

答案 1 :(得分:2)

我检查了你的代码。似乎toDoList = [[NSMutableArray arrayWithObject:@"Add a ToDo with the '+' button"] retain];[toDoList removeObjectAtIndex:[tableView selectedRow]];表现良好 我对你的问题的看法是关于表格视图。确保表视图始终包含选择。您可以在Interface Builder中或以编程方式进行设置。这是为了确保[toDoList removeObjectAtIndex:始终从表视图中接收值。

答案 2 :(得分:0)

在AppController.m中,您正在使用方法创建数组 arrayWithObject: 这将创建一个自动释放数组,将在某事后发布。所以改为使用initWithObjects:方法

相关问题