Re: -init never gets sent
Re: -init never gets sent
- Subject: Re: -init never gets sent
- From: Graham Cox <email@hidden>
- Date: Fri, 29 May 2009 11:25:55 +1000
On 29/05/2009, at 11:19 AM, Erg Consultant wrote:
- (id)init
{
if( !gReg )
{
if( ( self = [ super init ] ) )
{
// Zero out members...
keys = nil;
lastFlushTime = nil;
}
}
return self;
}
This is a little broken.
-init must always be allowed to run, so testing for the existence of
gReg is wrong. I know you're trying to create a kind of singleton, but
this isn't the way to do it.
Also, initialising members to zero isn't necessary, as alloc does that.
So, removing the unnecessary and incorrect things here, you end up with:
return [super init];
Hmmm... looks like you can dispose of init altogether. I assume your
object inherits from NSObject?
A good way to make a singleton that avoids a global is to use a class
method like so:
+ (MyObject*) singleton
{
static MyObject* sSingle = nil;
if( sSingle == nil )
sSingle = [[self alloc] init];
return sSingle;
}
_______________________________________________
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