开发者

Creating a "permanent" Cocoa object

I have an object factory that hands out instances of a few "constant," immutable objects. I'd like these objects to be protected against bad memory management by clients. This is how I've overridden the class's key methods. Am I missing anything (code or other considerations)?

- (id)retain
{
    return self;
开发者_开发百科}

- (NSUInteger)retainCount
{
    return UINT_MAX;
}

- (void)release
{
    // nothing.
}

Update for later Drive-by question readers: This was (by intention) a special-case, double-black-diamond Cocoa question. If you're trying to create a regular singleton, see the answers below regarding shared instances, etc. This question (and the chosen answer) falls into the "you should be sure you know what you're doing" before choosing this implementation strategy.


It sounds like you're trying to create a singleton. This is a very common pattern and there's been lots written about it. These links should tell you all you need to know:

http://www.mikeash.com/pyblog/friday-qa-2009-10-02-care-and-feeding-of-singletons.html

http://boredzo.org/blog/archives/2009-06-17/doing-it-wrong

And of course the Apple documentation here and here.


You may also want to override copyWithZone: and autorelease:

- (id)copyWithZone:(NSZone *)zone
{
    return self;
}

- (id)autorelease
{
    return self;
}


Hmmm, to really make it permanent:

- (void) dealloc
{
    return;
    [super dealloc]; // stop compiler warning
}

But, what advantage does this really have? Are your clients the kind that don't follow well-documented memory management rules?


The idea of breaking the retain/release contract like that has a real bad smell to it. Would something like keeping a reference to the singleton objects in the class object be good enough? You would thereby prevent the object from being released in normal code.

If you are just protecting against an accidental over-release a better strategy would be to fail fast and get the original problem fixed, would it not? I just don't like the solution breaking things worse to accommodate broken code.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜