2

我刚刚使用 Xcode 工具将我的应用程序从垃圾收集移植到了 ARC。当我的应用程序创建一个新窗口时,该窗口立即消失。在 GC 下,窗口仍然可见。

我知道在 ARC 中,任何没有指向它的强指针的对象都会消失。我有一个从我的 NSDocument 子类对象到属于它的窗口的强指针,但是 NSWindow 在创建后立即消失。

我需要一个指向新的 NSDocument 子类对象的强指针吗?如果是这样,该指针属于什么?

- (IBAction)importLegacyDocument:(id)sender{
    myDocument* theDocument = [[myDocument alloc]init];

    NSWindowController* theWindowController;
    theWindowController =[[NSWindowController alloc]
                          initWithWindowNibName:@"myDocument" owner: theDocument];
    [theDocument makeWindowControllers];
    [theDocument showWindows];
//WINDOW VANISHES IMMEDIATELY AFTER IT HAS BEEN CREATED
}

非常感谢大家提供任何信息!

4

2 回答 2

2

是的,您应该参考该文件。如果没有保留,您在方法内创建的任何对象都将被销毁。该NSWindowController代码中的实例也是如此。

@property (strong, nonatomic) myDocument *theDocument;
@property (strong, nonatomic) NSWindowController *theWindowController

(您AppDelegate将是声明这些属性的好地方)

然后将创建的实例分配给您的属性:

self.theDocument = [[myDocument alloc] init];
self.theWindowController = [[NSWindowController alloc] initWithWindowNibName:@"myDocument" owner:self.theDocument];

作为旁注 - Objective-C 约定是用大写字母命名类,所以myDocument应该是MyDocument

希望这可以帮助!

于 2013-07-07T02:39:17.673 回答
1

是的,该强引用的正确位置是 nsdocumentcontroller 单例。

您应该使用 nsdocumentcontroller 的方法而不是 alloc/init 创建新文档。这将自动将新文档添加到文档控制器并在文档关闭时将其删除。

于 2013-07-07T13:34:38.813 回答