2010-02-22 94 views
2

我学习可可,和我有一个问题:我想一个NSMutableArray的内容绑定到一个NSTableView,绑定的。我阅读了许多关于他们的文档,但我无法设法让他们工作(我的表格中没有显示任何内容)。绑定一个NSTableView到一个NSMutableArray

这里是事实:

我创建了一个简单的模型,叫做MTMTask其中包含2个属性,prioritytext

MTMTask.h

@interface MTMTask : NSObject { 
NSString *priority; 
NSString *text; 
} 

@property(copy) NSString* priority; 
@property(copy) NSString* text; 

- (id) initWithPriority :(NSString*)newPriority andText:(NSString*)newText; 

@end 

MTMTask.m

#import "MTMTask.h" 

@implementation MTMTask 

@synthesize text, priority; 

- (id) initWithPriority:(NSString *)newPriority andText:(NSString *)newText { 
if (self = [super init]) { 
    priority = newPriority; 
    text = newText; 
    return self; 
} 
return nil; 
} 

@end 

然后,我cre重复的信号MTMTaskController:

MTMTaskController.h

#import <Cocoa/Cocoa.h> 
#import "MTMTask.h" 

@interface MTMTaskController : NSObject { 
NSMutableArray *_tasksList; 
} 

- (NSMutableArray *) tasksList; 

@end 

MTMTaskController.m

#import "MTMTaskController.h" 

@implementation MTMTaskController 

- (void) awakeFromNib 
{ 
MTMTask *task1 = [[MTMTask alloc] initWithPriority:@"high" andText:@"Feed the hungry cat"]; 
MTMTask *task2 = [[MTMTask alloc] initWithPriority:@"low" andText:@"Visit my family"]; 

_tasksList = [[NSMutableArray alloc] initWithObjects:task1, task2, nil]; 
} 

- (NSMutableArray*) tasksList 
{ 
return _tasksList; 
} 

@end 

最后我编辑的MainMenu.xib:我添加了一个NSObject和它的类设置为MTMTaskController。然后我添加了一个名为TasksListController的NSArrayController,其内容出口绑定到MTMTaskController.tasksList。我也将其模式设置为Class和类名称MTMTask。我绑定了NSTableViewTasksListController两列的文本和优先级。

但是当我运行这个程序时,它并不是真的成功:表中没有任何东西显示出来。

你有没有关于我的问题的想法?我想我错过了一些东西,但我无法弄清楚什么。

在此先感谢!

+0

你有没有设置断点,以确保控制器和对象实际上正在创建?您可能忘记将控制器作为xib文件中的对象添加,在这种情况下'awakeFromNib'不会被调用。 – Abizern 2010-02-22 09:52:27

+0

刚刚尝试过:我在'awakeFromNib'中放了一个NSLog()调用,并将其显示在控制台中。看起来问题不在那里。 – Thomas 2010-02-22 09:57:42

回答

2

当你分配从笔尖在清醒控制器对象,您创建对象,将它们添加到一个数组,然后设置数组作为任务列表。

关于绑定的事情是你需要知道KVO(Key value observing),它是绑定对象知道绑定事物已经改变的机制。

在从笔尖方法你刚才设置直接在阵列不调用志愿清醒。

我已经创建了一个例子Xcode项目(Xcode的3.1),你可以download from here。这将创建任务列表和awakeFromNib方法我使用属性语法分配阵列,其负责国际志愿者组织的内为你的属性:

- (void)awakeFromNib { 
    Task *task1 = [[Task alloc] initWithPriority:@"high" andText:@"Feed the cat"]; 
    Task *task2 = [[Task alloc] initWithPriority:@"low" andText:@"Visit my familiy"]; 

    self.taskArray = [[NSMutableArray alloc] initWithObjects:task1, task2, nil]; 

}

或者,你可以夹在作业willChangeValueForKey:didChangeValueForKey:消息,但我会将它作为练习的对象。

+0

它工作得很好!非常感谢你!我想已经理解你的解释。我需要更频繁地使用@property。 – Thomas 2010-02-22 12:57:45

+0

谢谢你的解释!今天我遇到了同样的问题。 – nonamelive 2011-01-22 16:24:45

+0

你的解释也帮助了我。谢谢你为我节省一大笔头痛! – Dev 2012-06-07 07:33:32

相关问题