>> How can I create a Unit Test which tests such cases, e.g.:
>> 
>> Foo* foo;
>> @autoreleaspool {
>>   foo = [Foo new];
>>   [foo doSomething]; 
>>   foo = nil;   // should deallocate foo
>> }
>> ASSERT_DEALLOCATED_TRUE(foo);
> 
> Create a __weak reference to foo and assert that it is nil?

That's the easiest, but if anyone needs to do this with older environments 
where you don't have zeroing weak references you can also accomplish this using 
ObjC's associated objects. Just create a special tracker object whose -dealloc 
method informs you of its deallocation, then set that tracker on foo using 
"objc_setAssociatedObject". When foo deallocates so will the tracker object.

Basic idea:

@implementation XXDeallocTracker

+ (void) trackDeallocForObject:(id)watchObj
{
        XXDeallocTracker* tracker = [[XXDeallocTracker alloc] 
initTrackingObject:watchObj];
        [tracker release]; // watchObj now retains tracker by association, 
until watchObj deallocs
}

- (id) initTrackingObject:(id)obj
{
        if( self = [super init] ) {
                objc_setAssociatedObject( obj, &key, self, RETAIN );
        }
        return self;
}

- (void) dealloc
{
        // post NSNotification, call a block, or whatever you like to let the 
client know
        [super dealloc];
}

@end



@implementation XXTextCase

- (void) testEnsureDealloc
{
        id foo = [foo newFoo];
        [XXDeallocTracker trackDeallocForObject:foo];
        [foo doSomething];
        [foo release];
        // make sure notification was received, block was called, or whatever 
strategy the tracker employed
}

@end



That's typed into Mail and won't compile, but you get the idea.

~Martin



_______________________________________________

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Reply via email to