On 16-Apr-10, at 6:34 PM, Paul Sanders wrote:

Another way might be to provide a method in each class or subclass called, say, zeroIVars and code it as (typed in mail):

- (void) zeroIVars
{
    static ThisClass *clean_instance_of_this_class;

    assert ([self isMemberOfClass: [ThisClass class]);
    if (clean_instance_of_this_class == nil)
        clean_instance_of_this_class = [[ThisClass alloc] init];
    *self = *clean_instance_of_this_class;
}

Note that this should correctly preserve the object's isA pointer.

Although not strictly threadsafe, this should be good enough in practise - in the worst case it just leaks an object or two. The biggest danger, of course, would be to forget to implement zeroIVars for a subclass. That would be lethal, hence the assert.

This approach gives you the opportunity to end up with an object that is not just all zeroes (by way of the init method), and if a class needs some kind of cleanup that could be catered for too (perhaps by calling a method called, say, cleanup, which, unlike zeroIVars, is allowed to call super). But then it's not quite so lightweight...

An interesting approach. More overhead than my scheme, but I like that it lets you get an object which is not simply zeroed out.

If you declare zeroIVars as part a protocol, I believe the compiler will check that you have implemented it for all subclasses that adopt that protocol (can someone please confirm this):

@protocol MyLightweightReusableObjectProtocol

- (void) zeroIVars;

@end


@interface MyClass : NSObject <MyLightweightReusableObjectProtocol>

If you re-declare the protocol conformance with every subclass, then I think you are correct (but haven't tested that). But that just means you have to remember to re-declare the protocol conformance, which isn't really any better than having to remember to declare the method in the first place...

Ben Haller
McGill University

_______________________________________________

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:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

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

Reply via email to