Re: Singletons on Leopard with GC
Re: Singletons on Leopard with GC
- Subject: Re: Singletons on Leopard with GC
- From: Citizen <email@hidden>
- Date: Fri, 11 Apr 2008 10:18:39 +0100
Apple has added a comment about garbage-collected singletons in its
Cocoa Fundamentals Guide:
http://developer.apple.com/documentation/Cocoa/Conceptual/CocoaFundamentals/CocoaObjects/chapter_3_section_10.html
Basically you create a singleton as shown in the guide's example, but
in a garbage-collected environment you can leave out implementing the
release, retain, retainCount, and autorelease methods.
If you follow the Apple example you will need to implement a class
factory method, allocWithZone: and copyWithZone.
- Dave
On 10 Apr 2008, at 22:11, Karl Moskowski wrote:
I have a couple of classes for which I'd like to use the singleton
pattern.
I read some of the old posts on this list and at cocoadev.com about
approaches to take. They mention Apple's recommendations about
overriding retain, release, etc. to essentially turn them into no-
ops. However, they're from pre-Leopard days, and in a GC-required
app, the compiler automatically no-ops those methods.
I'm currently using something like this code in my implementations:
static MyClass *sharedInstance;
+ (MyClass *)sharedInstance {
if (!sharedInstance)
sharedInstance = [[self alloc] init];
return sharedInstance;
}
- (id)init {
if (!sharedInstance)
sharedInstance = [super init];
return sharedInstance;
}
My goal is to ensure that [MyClass sharedInstance] and [[MyClass
alloc] init] return the same singleton object. Furthermore, I'd like
to ensure that an object instantiated in a NIB is the sharedInstance
too. So far, it seems to work, but I'm afraid I've missed something.
Any suggestions? Thanks.
----
Karl Moskowski <email@hidden>
Voodoo Ergonomics Inc. <http://voodooergonomics.com/>
_______________________________________________
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
_______________________________________________
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