子类化NSArrayController的原因是什么?

时间:2011-04-03 06:28:24

标签: cocoa subclass cocoa-bindings nsarraycontroller

我正在努力改进我的KVC / KVO / Cocoa-Bindings-fu,并想知道将NSArrayController子类化的原因是什么?

5 个答案:

答案 0 :(得分:17)

我有一个自定义的NSArrayController子类,它执行一大堆任务。我选择在那里实现这些东西,因为我可以享受绑定和东西的完全舒适。以下是我现在使用的内容:

  • 有时必须隐藏某些项目,并且必须显示一些项目
  • 我在控制器中执行自定义排序(即分组)
  • 它由与其返回的不同类型的项目提供(获取项目,返回项目节点 - 转发大多数内容的虚拟对象)
  • 我还用它来保存当前显示的过滤条件和搜索选项
  • 此外,我添加了NSTableView委托和数据源支持,允许拖动和放大在控制器中删除实现
  • 我还在那里自定义单元格的工具提示

是的,等等。基本上这一切归结为这个本质:子类NSArrayController,如果你想要不同的数据输出

最高

答案 1 :(得分:9)

使用带有表视图的数组控制器时,我喜欢做的一件事是覆盖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子类的控制器来做类似的事情;这只是我想出的第一种方式。

答案 2 :(得分:1)

我有一个应用程序需要在用户添加对象时设置隐藏文件名 - 自定义ArrayController类中的add方法只是执行此操作的地方。

编辑 - 实际上,重新阅读我的Hillegas,覆盖newObject是更好的方法。它仍然需要NSArrayController的子类。

答案 3 :(得分:0)

我将数组控制器子类化为在调用时返回所需的对象 - (id)newObject;

通常你有.h&项目中每个类的.m文件和数组控制器通过读取这些文件,根据类的名称创建特定对象。

但是当你只有一个.h .m文件或​​一个类(例如:Entity)可以返回任何对象(例如:员工,客户,通过读取存储的模态定义)基于你的neeed,你必须子类化arraycontroller因为无论您是需要员工对象还是客户对象,类名都保持不变(实体)。

答案 4 :(得分:0)

我使用NSArrayController的子类来命名撤消/重做操作,以便在我的核心数据应用程序中添加和删除对象。
(这不是我自己的想法,信用额归功于@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*"];
}