gpt4 book ai didi

objective-c - NSDocumentController currentDocument 返回 nil

转载 作者:太空狗 更新时间:2023-10-30 03:29:12 24 4
gpt4 key购买 nike

我正在开发我的第一个基于 Mac 文档的应用程序。

我继承了 NSDocument,重新实现了一些方法,例如

- (BOOL)readFromURL:(NSURL *)absoluteURL ofType:(NSString *)typeName error:(NSError **)outError;
- (BOOL)writeToURL:(NSURL *)absoluteURL ofType:(NSString *)typeName error:(NSError **)outError;
- (void)makeWindowControllers;

主窗口 Controller 是 NSWindowsController 的子类,它包含两个 NSViewController 子类。

我面临的问题是我需要从这些 View Controller 访问当前文档。我所做的就是打电话

MyDocument *myDocument = [[NSDocumentController sharedController] currentDocument];

首先,在启动应用程序后,会立即创建一个新文档。然后,创建主窗口及其 View Controller ,但上面的方法返回 nil。这是我得到的日志(使用 NSLog):

Just created this new document: <MyDocument: 0x10040ff10>
I'm in a view controller and current document is (null)

之后,创建一个新文档并调用此方法会产生一个非 nil 指针,但它不会指向正确的文档,而是指向第一个文档:

Just created this new document: <MyDocument: 0x100437e10>
I'm in a view controller and current document is <MyDocument: 0x10040ff10>

请注意,在创建第二个文档后,currentDocument 指向第一个文档而不是第二个文档。

知道我在这里遗漏了什么或做错了什么吗?何时为 NSDocumentController 设置 currentDocument

最佳答案

(我将保留之前的答案,因为它在询问 NSView 的子类时回答了问题,但现在原始发帖人已声明他使用的是 NSViewController,因此有不同的考虑因素)。

NSViewController 控制 View 的情况下,NSViewController 旨在使用 representedObject 属性附加到其数据。此抽象旨在由 NSViewController 的包含 Controller 管理,这听起来像是您的 NSWindowController

根据您想要/需要提供多少封装,您可以将文档推送到 NSViewController(如果它们对整个文档进行操作)或仅推送与特定 NSViewController 相关的文档中的信息。

例如,我假设有一款软件可以编辑有关火车的设计信息:引擎、车厢和守车。 NSDocument 子类包含一个引擎对象、一个守车对象和 0 个或多个汽车对象。在这种情况下,您可能有 3 个 NSView,每个都有自己的 NSViewController 来处理从它们的对象移入和移出 View 的数据。

NSWindowController 处理将每个 NSViewControllerrepresentedObject 设置为它理解的对象。例如,当 View 完成加载时,窗口 Controller 将:

    [engineViewController setRepresentedObject: engine];
[cabooseViewController setRepresentedObject: caboose];

Then, you can use an NSTableView to show the list of cars, and (when a car is being viewed), the window controller could then use [carViewController setRepresentedObject: car]; when the selection已更改(或者您可以使用绑定(bind),具体取决于代码的结构)。

这样,您就可以充分利用 MVC 范例,因为 Controller 会根据需要将 View 链接到模型,但只有顶层 NSWindowController 才能真正理解文档结构。

关于objective-c - NSDocumentController currentDocument 返回 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8912314/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com