Re: Is Apple's singleton sample code correct?
Re: Is Apple's singleton sample code correct?
- Subject: Re: Is Apple's singleton sample code correct?
- From: Shaun Wexler <email@hidden>
- Date: Thu, 1 Dec 2005 20:02:24 -0800
On Dec 1, 2005, at 7:50 PM, Greg Titus wrote:
You are breaking the retain/release rules here. All these methods
should do a retain before returning.
Good catch. I had blindly copy/pasted those methods from my immortal
class. Fixed, with modifications, below:
@interface MortalSingleton : NSObject
@end
//
========================================================================
=======================
//
// MortalSingleton.m
//
// Created by Shaun Wexler on Thu Dev 01 2005.
// Copyright (c) 2005 SKW Development. All rights reserved.
//
//
========================================================================
=======================
@implementation MortalSingleton
static NSMutableDictionary *singletons = nil;
+ (void)initialize
{
@synchronized([MortalSingleton class]) {
if (!singletons) {
singletons = [[NSMutableDictionary alloc] initWithCapacity:8];
}
}
}
+ (id)allocWithZone:(NSZone *)zone
{
id instance = nil;
@synchronized(singletons) {
NSValue *singleton;
if ((singleton = [singletons objectForKey:self])) {
instance = [[singleton nonretainedObjectValue] retain];
} else if ((instance = NSAllocateObject(self, 0, zone))) {
[singletons setObject:[NSValue
valueWithNonRetainedObject:instance] forKey:self];
}
}
return instance;
}
- (id)copy
{
return [self retain];
}
- (id)copyWithZone:(NSZone *)zone
{
return [self retain];
}
- (id)mutableCopy
{
return [self retain];
}
- (id)mutableCopyWithZone:(NSZone *)zone
{
return [self retain];
}
- (void)dealloc
{
@synchronized(singletons) {
[singletons removeObjectForKey:[self class]];
}
[super dealloc];
}
@end
--
Shaun Wexler
MacFOH
http://www.macfoh.com
"A person who never made a mistake never tried anything new." -
Albert Einstein
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Cocoa-dev mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden