在您看到以下问题中的单词之前,请停止按retainCount
OK ,请跳到底部的EDIT ,我已声明我已停止使用它。
我的 Cocoa App 使用MRR创建了许多全局资源,我在调用main()
之前加载了这些资源。NSApplicationMain()
由于NSApplicationMain()
没有返回,我已经使用 对这些资源进行了清理atexit()
,如下所示:
atexit(cleanup);
if (![CocoaUtil initCocoaUtil] ||
![PreferenceController initPreferenceController] ||
![ResourceManager initResourceManager])
{
criticalAlertPanel(@"Failed to initialize application",
@"Failed to initialize application");
return 4;
}
retval = NSApplicationMain(argc, (const char **)argv);
然而,在我的子类中的cleanup()
任何视图被调用之前被调用(我没有日志消息来显示这一点),因此全局资源中对象的引用计数有时是. 我过于谨慎并试图通过使用这种方法来释放我的全局资源来预防内存泄漏:NSDocument
dealloc
> 1
+ (void)fullRelease:(id)obj
format:(NSString *)format, ...
{
if (obj == nil)
return;
NSUInteger retainCount = [obj retainCount];
if (retainCount > 1)
{
va_list va;
va_start(va, format);
NSString *objDesc = [[NSString alloc] initWithFormat:format arguments:va];
logwrn(@"%@ has a reference count of %lu", objDesc, retainCount);
[objDesc release];
}
while (retainCount > 0)
{
[obj release];
retainCount--;
}
}
我的日志显示以下内容:
12:15:04.954 INF -[AppController applicationDidFinishLaunching:] Application launched
12:15:06.702 INF -[AppController applicationShouldTerminate:] Application terminating
12:15:06.703 INF -[AppController applicationWillTerminate:] Application terminating
12:15:06.705 DBG cleanup Cleaning-up
12:15:06.705 INF +[ResourceManager finiResourceManager] Cleaning up
12:15:06.709 WRN +[CocoaUtil fullRelease:format:] _images[2] has a reference count of 2
12:15:06.709 WRN +[CocoaUtil fullRelease:format:] _images[3] has a reference count of 2
12:15:06.709 WRN +[CocoaUtil fullRelease:format:] _images[4] has a reference count of 2
12:15:06.710 WRN +[CocoaUtil fullRelease:format:] _images[5] has a reference count of 2
12:15:06.710 WRN +[CocoaUtil fullRelease:format:] _images[6] has a reference count of 2
12:15:06.710 WRN +[CocoaUtil fullRelease:format:] _images[7] has a reference count of 2
12:15:06.711 WRN +[CocoaUtil fullRelease:format:] _images[8] has a reference count of 2
12:15:06.711 WRN +[CocoaUtil fullRelease:format:] _images[9] has a reference count of 2
12:15:06.721 DBG +[PreferenceController finiPreferenceController] Cleaning up
12:15:06.721 DBG +[CocoaUtil finiCocoaUtil] Cleaning up
我的问题(终于!)是:
NSDocument
有没有办法确保在所有实例都被销毁后清理我的全局资源并停止收到这些假阴性?
编辑:我已经取消了fullRelease
调用,只是release
对我的资源执行了正常操作,并且 Instruments 没有检测到任何内存泄漏,所以一切正常,但我很好奇为什么这些NSDocument
对象在调用之前似乎没有被释放atexit()
。