我想我已經找到了答案。垃圾收集器的源代碼似乎並不可用,但頭文件中聲明爲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來測試我的假設。米):
#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
和運行爲./gcbridgetest
,它提供了以下的輸出,確認啓用/ 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