Next article: Friday Q&A 2010-07-30: Zeroing Weak References to CoreFoundation Objects
Previous article: Friday Q&A 2010-07-16: Zeroing Weak References in Objective-C
Tags: code hack objectivec sourcecode
I'm extremely excited to announce a new library for Cocoa and Cocoa Touch development:
MAZeroingWeakRef. In short, it's a library which allows zeroing weak references to be used in retain/release Cocoa code. This has all sorts of uses and should make retain/release coding less painful. While I discussed this in detail in my Friday Q&A post this week, I also want to make a separate announcement for people who don't want to read through all of the horrible details.
A zeroing weak reference is a reference to an object which does not prevent that object from being destroyed (in other words, it's not retained), and which automatically becomes
nil once the object is destroyed. To use
MAZeroingWeakRef, you simply create one using
MAZeroingWeakRef *ref = [[MAZeroingWeakRef alloc] initWithTarget: object];
NSLog(@"Target is %@", [ref target]);
-targetwill return it. Once it is destroyed,
-targetreturns a reference that has been retained and autoreleased, ensuring that the returned object will remain valid as you use it even if the last strong reference to it has been released in another thread while you work.
You can get
MAZeroingWeakRef from my public subversion repository:
MAZeroingWeakRef should compile and run on any OS with the "modern" runtime APIs, which is basically 10.5 and up, and any iOS version. Blocks support is needed to enable the cleanup block functionality (which allows running arbitrary code when the reference is destroyed) but everything else will work without it.
If you use
MAZeroingWeakRef on iOS, you may want to set
MAZeroingWeakRef.m. This prevents
MAZeroingWeakRef from being able to target CoreFoundation bridged objects, but also avoids the use of private API, which Apple can sometimes be unfriendly about. This is not a big disadvantage, as it's extremely rare to have weak references to CF objects.
I hope that this library will prove useful!
Why don't you use message forwarding mechanism instead of [[ref target] message]?
And it's fine if you ask about code, but since more discussion is happening in that other post, you may want to ask over there instead.
Comments RSS feed for this page
Add your thoughts, post a comment:
Spam and off-topic posts will be deleted without notice. Culprits may be publicly humiliated at my sole discretion.