Re: Zeroing out instance variables
Re: Zeroing out instance variables
- Subject: Re: Zeroing out instance variables
- From: "Paul Sanders" <email@hidden>
- Date: Fri, 16 Apr 2010 23:34:53 +0100
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...
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>
...
Paul Sanders.
----- Original Message -----
From: "Ben Haller" <email@hidden>
To: "Cocoa List" <email@hidden>
Sent: Friday, April 16, 2010 10:29 PM
Subject: Re: Zeroing out instance variables
> 3. bzero(individual + individualIvarsOffset, individualIvarsSize);
This should cast "individual" to void* before doing the pointer
arithmetic, of course.
> So, thoughts? Am I insane? Is the above scheme safe? Is there a
> better way? Thanks for any feedback!
I should note that the scheme described does appear to work
correctly on 10.5, at least.
Ben Haller
McGill University
_______________________________________________
Cocoa-dev mailing list (email@hidden)
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:
This email sent to email@hidden