2011-04-03 87 views
14

我想改善我的KVC/KVO/Cocoa-Bindings-fu,並想知道可能是什麼原因來繼承NSArrayController?子類化NSArrayController的原因是什麼?

+0

太糟糕了沒有更多的答覆;這是一個有趣的問題,而我那愚蠢的小技巧幾乎不能抓住主題的表面。 – 2011-04-05 09:24:57

+0

確實。我會嘗試在線共享... – Eimantas 2011-04-05 10:06:19

回答

16

我有一個自定義NSArrayController子類,執行一大堆任務。我選擇在那裏實現這些東西,因爲我可以享受綁定和東西的全部舒適。這是我現在用這個:

  • 有時候一些項目必須被隱藏,有些必須顯示
  • 我執行自定義排序(即分組)控制器
  • 它是由一個項目喂不同的類比它返回(獲取項目,返回項目節點 - 虛擬對象,轉發最多的東西)
  • 我也用它來保存當前顯示的篩選條件和搜索選項
  • 此外,我添加了NSTableView委託和數據源支持,允許拖動在控制器
  • 我還可以自定義工具提示的細胞中有

呀,等等0降權的實現。基本上,這一切歸結爲這個精髓:子類NSArrayController的,如果你想不同的數據進行比你

把最大

+0

信息性列表Max;你在做什麼來定製工具提示? – 2011-05-07 16:36:08

+0

@Mike Abdullah:它是NSTableView委託的一部分,我只是實現了這個方法:'tableView:toolTipForCell:rect:tableColumn:row:mouseLocation:' – 2011-05-12 10:44:04

8

使用帶有表格視圖的陣列控制器時,我喜歡做的一件事是覆蓋add:以發佈通知,以便選擇新項目並立即打開並進行編輯。我實際上是在CocoaDev張貼這在前段時間:

// Subclass of NSArrayController 

- (void)awakeFromNib 
{ 
    [[NSNotificationCenter defaultCenter] addObserver: self 
              selector: @selector(objectAdded:) 
               name: @"Object Added" 
               object: self] 
} 

- (void)add: (id)sender 
{ 
    [super add: sender] 
    NSNotification * note = [NSNotification 
           notificationWithName: @"Object Added" 
               object: self] 
    // The add method doesn't really take effect until this run loop ends, 
    // (see NSArrayController docs) so the notification needs 
    // to wait to post. Thus, enqueue with NSPostWhenIdle 
    [[NSNotificationQueue defaultQueue] enqueueNotification: note 
               postingStyle: NSPostWhenIdle] 
} 

- (void)objectAdded: (NSNotification *)note 
{ 
    // when the notification finally arrives, tell the table to edit 
    [[self contentTable] editColumn:0 
            row:[self selectionIndex] 
           withEvent:nil 
           select:YES] 
} 

當然,這是可以做到與控制器,這不是一個NSArrayController子類相似;這只是我想出的第一種方式。

+0

您可以重寫'-addObject:'而不是'-add:'並正常發佈通知 – 2011-05-07 16:37:09

1

我有一個應用程序,當用戶添加一個對象時需要設置一個隱藏的文件名 - 自定義ArrayController類中的add方法只是這樣做的地方。

編輯 - 其實,重新讀我的Hillegas,重寫newObject是更好的方法。但它仍然需要NSArrayController的子類。

0

我子類陣列控制器在調用返回所需的對象 - (ID)NEWOBJECT;

正常情況下,您的項目中的每個類都有.h &.m文件,並且陣列控制器通過讀取這些文件來根據類的名稱創建特定的對象。

但是,如果您只有一個.h.m文件或​​基於您的neeed可以返回任何對象(例如:employee,customer,通過讀取存儲的模式定義)的類(例如:Entity),則必須子類arraycontroller,因爲類名稱保持不變(實體)是否需要員工對象或客戶對象。

0

我使用NSArrayController的子類來命名用於在我的Core Data應用程序中添加和刪除對象的撤銷/重做操作。
(這不是我自己的想法,信貸發給用戶@MikeD誰回答my question on this matter。)

重寫- newObject方法。

- (id)newObject 
{ 
    id newObj = [super newObject]; 

    NSUndoManager *undoManager = [[[NSApp delegate] window] undoManager]; 
    [undoManager setActionName:@"Add *insert custom name*"]; 

    return newObj; 
} 

也是- remove:sender方法。

- (void)remove:(id)sender 
{ 
    [super remove:sender]; 

    NSUndoManager *undoManager = [[[NSApp delegate] window] undoManager]; 
    [undoManager setActionName:@"Remove *insert custom name*"]; 
}