There is a class GCObject from which you could inherit your own
classes. This class implements the GarbageCollecting protocol.
Using this class, you could write a class whose instances hold other objects. This class is safe to cyclic references. Here is its implementation:
@interface MyGCObject : GCObject
{
id object;
BOOL isGarbageCollectable;
}
- (void)setObject:(id)anObject;
- (id)object;
@end
@implementation MyGCObject
- (void)setObject:(id)anObject
{
[anObject retain];
[object release];
object = anObject;
isGarbageCollectable = [object isGarbageCollectable];
}
- (id)object
{
return object;
}
- (void)decrementRefCountOfContainedObjects
{
[object gcDecrementRefCount];
}
- (BOOL)incrementRefCountOfContainedObjects
{
if(![super incrementRefCountOfContainedObjects])
return NO;
[object gcIncrementRefCount];
[object incrementRefCountOfContainedObjects];
return YES;
}
- (void)dealloc
{
if(!isGarbageCollectable)
[object release];
[super dealloc];
}
@end
There are also concrete subclasses of NSArray and
NSDictionary named GCArray and GCDictionary
respectively, together with their mutable classes GCMutableArray
and GCMutableDictionary. Their instances could hold both normal
and garbage collectable objects.
Go to the first, previous, next, last section, table of contents.