5
Weak reference class for Cocoa/GNUstep/OpenStep. As it stands, this will not
6
work as a weak reference in a garbage-collected environment.
8
A weak reference allows code to maintain a reference to an object while
9
allowing the object to reach a retain count of zero and deallocate itself.
10
To function, the referenced object must implement the OOWeakReferenceSupport
13
Client use is extremely simple: to get a weak reference to the object, call
14
-weakRetain and use the returned proxy instead of the actual object. When
15
finished, release the proxy. Messages sent to the proxy will be forwarded as
16
long as the underlying object exists; beyond that, they will act exactly like
17
messages to nil. (IMPORTANT: this means messages returning floating-point or
18
struct values have undefined return values, so use -weakRefObjectStillExists
19
or -weakRefUnderlyingObject in such cases.) Example:
21
@interface ThingWatcher: NSObject
27
@implementation ThingWatcher
28
- (void)setThing:(Thing *)aThing
31
thing = [aThing weakRetain];
47
Note that the only reference to OOWeakReference being involved is the call to
48
weakRetain instead of retain. However, the following would not work:
52
Additionally, it is not possible to access instance variables directly -- but
53
then, that's a filthy habit.
55
OOWeakReferenceSupport implementation is also simple:
57
@interface Thing: NSObject <OOWeakReferenceSupport>
59
OOWeakReference *weakSelf;
66
if (weakSelf == nil) weakSelf = [OOWeakReference weakRefWithObject:self];
67
return [weakSelf retain];
70
- (void)weakRefDied:(OOWeakReference *)weakRef
72
if (weakRef == weakSelf) weakSelf = nil;
77
[weakSelf weakRefDrop]; // Very important!
88
Written by Jens Ayton in 2007 for Oolite.
89
This code is hereby placed in the public domain.
93
#import <Foundation/Foundation.h>
95
@class OOWeakReference;
98
@protocol OOWeakReferenceSupport <NSObject>
100
- (id)weakRetain; // Returns a retained OOWeakReference, which should be released when finished with.
101
- (void)weakRefDied:(OOWeakReference *)weakRef;
106
@interface OOWeakReference: NSProxy
108
id<OOWeakReferenceSupport> _object;
111
- (BOOL)weakRefObjectStillExists;
112
- (id)weakRefUnderlyingObject;
114
- (id)weakRetain; // Returns self for weakrefs.
116
// For referred object only:
117
+ (id)weakRefWithObject:(id<OOWeakReferenceSupport>)object;
123
@interface NSObject (OOWeakReference)
125
- (BOOL)weakRefObjectStillExists; // Always YES for non-weakrefs. ObjC semantics causes it to return NO for nil, so it acts as an existence check.
126
- (id)weakRefUnderlyingObject; // Always self for non-weakrefs (and of course nil for nil).
132
Simple object implementing OOWeakReferenceSupport, to subclass. This
133
provides a full implementation for simplicity, but keep in mind that the
134
protocol can be implemented by any class.
136
@interface OOWeakRefObject: NSObject <OOWeakReferenceSupport>
138
OOWeakReference *weakSelf;