【问题标题】:nsdocument subclass variable is somehow reset to nil after a proper initialization: why?nsdocument 子类变量在正确初始化后以某种方式重置为 nil:为什么?
【发布时间】:2012-06-30 21:22:00
【问题描述】:

我有一个消失的指针db;在创建NSDocument 期间正确设置了该值,但此刻我想打开一个子窗口,该值已更改为nil!我在NSDocument 子类中有以下内容:

 @interface MW_Document : NSDocument
 {
     MW_WorkerWindowController *workerController;
     __strong MW_db *db;
 }

 - (IBAction)showWorkerManagementPanel:(id)sender;
 //- (IBAction)showSkillManagementPanel:(id)sender;

实现包含以下内容:

 - (void)windowControllerDidLoadNib:(NSWindowController *)aController
 {
     [super windowControllerDidLoadNib:aController];
     if (![self db]) {
         db = [[MW_db alloc] init];
         NSLog ( @"Debug - Init of db: [%ld]", db ); // never mind the casting problem
     }
 }

db 指向的不是 nil,而是一个真正的地址。

稍后,我想打开一个窗口并在同一个NSDocument子类的实现中拥有这个:

 - (IBAction)showWorkerManagementWindow:(id)sender
 {
     if ( !workerController) {
         workerController = [[MW_WorkerWindowController alloc] initWithDb:db];
     }
     [workerController showWindow:self];
 }

我在第一行打了一个断点,看看db的值。它为零,但我不知道为什么。谁能给我解释一下?

【问题讨论】:

  • 您是否尝试在windowControllerDidLoadNib: 中设置断点?更具体地说,您确定db = [[MW_db alloc] init]; 实际上被称为之前 workerController = [[MW_WorkerWindowController alloc] initWithDb:db];?可能是 workerController 在调用 -[showWindow:] 之前不会加载其 NIB。

标签: macos cocoa nsdocument nswindowcontroller


【解决方案1】:

你可以实现一个惰性访问器:

- (MW_db *)db
{
    if (db == nil) {
        db = [[MW_db alloc] init];
    }
    return db;
}

然后用它代替 ivar:

workerController = [[MW_WorkerWindowController alloc] initWithDb:[self db]];

【讨论】:

  • 这种惰性访问器是 ivar 初始化的一个很好的通用替代方案吗?我的猜测是它对性能不好,但它对于调试像当前这样的问题很有用。对吗?
  • 视情况而定,但大多数时候惰性 getter 是 -[init] 中直接 ivar 初始化的最佳替代方案。而且它们对性能特别有好处,因为你malloc内存只有在你真正需要一个对象的时候。所以,如果你正确地实现了惰性访问,应用程序的内存占用将尽可能小。
  • 每次请求值时检查 nil 怎么样?这可能非常便宜,在这种情况下,您在上面列出的内存管理优势更为重要!你能评论一下 nil-check 的计算成本有多大吗?
  • 这和比较两个整数是一样的,所以它在计算上一定很便宜。无论如何,您在编写代码时不应该担心这一点。首先,使其可读和工作,然后才使用 Instruments 进行优化。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-27
  • 1970-01-01
  • 2017-10-03
  • 1970-01-01
  • 2023-01-17
相关资源
最近更新 更多