我想我找到了答案。垃圾收集器的源代码似乎不可用,但声明接口的头文件NSGarbageCollector
包含NSGarbageCollector.h
以下Foundation.framework
内容:
// references outside the heap, globals, and the stack, e.g. unscanned memory, malloc memory, must be tracked by the collector
- (void)disableCollectorForPointer:(void *)ptr; // this pointer will not be collected...
- (void)enableCollectorForPointer:(void *)ptr; // ...until this (stacking) call is made
请注意“堆叠”注释 - 我认为这意味着调用确实被计算在内?更多证据仍然欢迎!
更新:
为了确定这一点,我决定使用一个小测试程序(gcbridgetest.m)来测试我的假设:
#import <Foundation/Foundation.h>
@interface PJGarbageCollectionTest : NSObject
@end
@implementation PJGarbageCollectionTest
- (id)init
{
self = [super init];
if (!self) return nil;
NSLog(@"%@ -init", self);
return self;
}
- (void)finalize
{
NSLog(@"%@ -finalize", self);
[super finalize];
}
@end
static void* ext_ptr1 = NULL;
static void* ext_ptr2 = NULL;
static void create()
{
PJGarbageCollectionTest* test = [[PJGarbageCollectionTest alloc] init];
[[NSGarbageCollector defaultCollector] disableCollectorForPointer:test];
ext_ptr1 = test;
[[NSGarbageCollector defaultCollector] disableCollectorForPointer:test];
ext_ptr2 = test;
}
static void killref(void** ext_ptr)
{
[[NSGarbageCollector defaultCollector] enableCollectorForPointer:*ext_ptr];
*ext_ptr = NULL;
}
int main()
{
NSLog(@"collector: %@", [NSGarbageCollector defaultCollector]);
create();
NSLog(@"Collecting with 2 external references");
[[NSGarbageCollector defaultCollector] collectExhaustively];
killref(&ext_ptr1);
NSLog(@"Collecting with 1 external reference");
[[NSGarbageCollector defaultCollector] collectExhaustively];
killref(&ext_ptr2);
NSLog(@"Collecting with 0 external references");
[[NSGarbageCollector defaultCollector] collectExhaustively];
return 0;
}
编译gcc -fobjc-gc-only -g -Wall -Wextra -ObjC gcbridgetest.m -framework Foundation -o gcbridgetest
并运行 as ./gcbridgetest
,它给出以下输出,确认 enable/disableCollectorForPointer: 调用确实被计算在内:
2012-06-12 16:08:08.278 gcbridgetest[29712:903] collector: <NSGarbageCollector: 0x20000f420>
2012-06-12 16:08:08.281 gcbridgetest[29712:903] <PJGarbageCollectionTest: 0x20000ee60> -init
2012-06-12 16:08:08.284 gcbridgetest[29712:903] Collecting with 2 external references
2012-06-12 16:08:08.285 gcbridgetest[29712:903] Collecting with 1 external reference
2012-06-12 16:08:08.286 gcbridgetest[29712:903] Collecting with 0 external references
2012-06-12 16:08:08.286 gcbridgetest[29712:903] <PJGarbageCollectionTest: 0x20000ee60> -finalize