2010-02-22 85 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