【发布时间】:2011-08-15 02:42:14
【问题描述】:
我在使用下面的超级简单代码时遇到了完全出乎意料的计时问题。其中一个变量是自动释放的,我不知道为什么。我没有使用 autorelease、KVO 等。它不应该发生。
WindowController 设置为 @property (retain)'d of MainController。
在MainController 的-dealloc 中,我做self.windowController = nil;
但是,它一直等到自动释放池被刷新以释放 windowController。我希望在 self.windowController = nil 完成后立即调用 WindowController 的 dealloc。即使我将 [mainController release] 包装在 NSAutoreleasePool 中,它仍然不会立即释放。
为什么会这样?
这对于@property / NSWindowController 来说似乎不是正确的行为。我错过了什么吗?
更正:它不是绑定。我正式不知道问题出在哪里。
主驱动:
[[MainController new] release];
MainController.h:
#import <Foundation/Foundation.h>
#import "WindowControllerSubclass.h"
@interface MainController : NSObject {
WindowControllerSubclass *wc;
}
@property (retain) WindowControllerSubclass *wc;
@end
MainController.m:
#import "MainController.h"
@implementation MainController
@synthesize wc;
- (id)init {
if (self = [super init]) {
// This is problem here >>> If I assign directly to wc, then it's not added to autorelease pool
self.wc = [[WindowControllerSubclass alloc] init];
[self.wc release]; // since it's (retain)'d
}
return self;
}
- (void) dealloc {
self.wc = nil;
NSLog(@"%@ deallocd (should be called after WC's dealloc)", [self className]);
}
@end
MainWindowControllerSubclass.h:
#import <Cocoa/Cocoa.h>
@interface WindowControllerSubclass : NSObject /* Not even NSWindowController */
@end
MainWindowControllerSubclass.m:
#import "WindowControllerSubclass.h"
@implementation WindowControllerSubclass
- (void) dealloc {
NSLog(@"%@ deallocd", [self className]);
}
@end
【问题讨论】:
-
我希望这是一个错字:
[[MainController new] release];。如果没有,这是一个主要问题,因为您会立即释放您正在创建的对象。 -
目前无法确定(手头没有 Mac),但属性的 getter 可能实现为
[[wc retain] autorelease]。这是 getter 的常见模式。 -
@Rob。这不是一个错字。我这样做是为了测试 MainController。它需要以正确的顺序显示 nslog。这就是这个简单问题示例的重点。
-
您可以覆盖控制器中的
autorelease方法,设置断点并查看谁以及何时执行此操作。 -
@Eugene,你猜对了。请参阅我编辑的答案。
标签: objective-c cocoa xcode4 nsautoreleasepool nswindowcontroller