将nsarraycontroller绑定到nsobjectcontroller,选择,内容的程序化等价物

时间:2013-06-04 19:35:55

标签: objective-c cocoa core-data cocoa-bindings

我将我的UI分成了各种nib文件。

现在,我使用两个nswindowcontroller子类与nsarraycontrollernsobjectcontroller IBOutlets。 nwwindowcontrollers是各自笔尖中的文件所有者。

控制器在IntefaceBuilder(IB)中分配。

以前在一个笔尖中,我有一个雇员nsarraycontroller与单个雇员nsobjectcontroller的绑定,使用'selection'的控制键和'self'的modelkeypath

现在,我尝试通过代码“绑定”它们,因此

- (IBOutlet) showEmployeeWindow:(id)sender;

//load a window from a nib file.
    ...

// Get the employee arraycontroller.
NSArrayController *employeesController = [employeesWindowController employeeArrayController];  

// Get the selected employee from the employeeS controller
id employee = [empController selection]; 

//now the employee 
NSObjectController *emplController = [singleEmployeeWindowController employeeController];

//Set the content object of the employee controller as the nsset called employees.
[emplController setContent: employee]; 

//Show the window.
[singleEmployeeWindowController showWindow:sender];

    ...

}

问题。

调试确实显示所选员工的不同内存地址。 即行

id employee = [empController selection]; 
// Get the selected employee from the employeeS controller

似乎有一个不同的员工。

但 我一直认为第一个员工从来都不是选定的员工。

选定的员工永远不会被设置为内容 - 或者更确切地说,所选员工不会替换默认的第一个员工。

请注意,每个nswindowcontroller都通过nsdocument设置了nsmanagedobject上下文。它是笔尖中的文件所有者。

1 个答案:

答案 0 :(得分:4)

通常不是这样。将头发拉出2天后。问一个问题然后在半小时内回答答案。

所以秘密基本上是可可绑定,特别是Key Value Bindings

该文档是典型的yackademic yadda yadda。级联线索实际上来自a similar stack overflow question

因此,所有人需要做的就是像这样将两个控制器连接在一起。

NSArrayController *source = [employeesWindowController employeeArrayController]];
NSObjectController *destination = [singleEmployeeWindowController employeeController];

[destination bind:@"contentObject" toObject:source withKeyPath:@"selection.self" options:nil];

语法遵循Interface Builder绑定的语法。

Bind to: Content Object 
Content Key: selection
ModelKeyPath: self

所以这是一个简单的单线。

NSLabel绑定到Controller。在IB

Bind to: Value 
Content Key: selection
ModelKeyPath: name

在代码中,

[label bind:@"value" toObject:controllerRef withKeyPath:@"selection.name" options:nil];

这些选项模仿“不适用键的提升”等等。有关详细信息,请参阅yackademic文本。