YosiFZ
YosiFZ

Reputation: 7900

Do I need to release my singleton object?

I have a singleton object in my app:

+ (id)shared {
    @synchronized(self) {
        if (sharedDownloadFirstData == nil)
            sharedDownloadFirstData = [[self alloc] init];
    }
    return sharedDownloadFirstData;
}

- (id) init {
    if (self = [super init]) {

    }
    return self;
}

And I want to know if I need to realese it (I am not using ARC). To do that I am using:

[[DownloadFirstData shared] release];

Did I need to release this object? I have an array and other stuff in the object that I need to release.

Upvotes: 1

Views: 1027

Answers (2)

Brian Nickel
Brian Nickel

Reputation: 27550

In Objective-C, you should only ever call release on an object you own. This typically means an object you've created with alloc, init, copy or mutableCopy or otherwise called retain on. Here, the consumer of [DownloadFirstData shared] didn't call any of those functions and is not responsible for releasing it. You will see this any time you call [UIColor blackColor], for instance.

You may want to call retain on such an object, if you are crossing autorelease boundaries or are just not sure of the lifetime:

DownloadFirstData *local = [[DownloadFirstData shared] retain];
...
[local release];

In this case, you've taken ownership and are responsible for releasing.

But what about the definition of shared? When you define a method not using init..., you are typically responsible for leaving with a release count of 0, with something like [[self alloc] init] autorelease]. This is not the case for the singleton because your goal is for it to always exist and therefore always have a non-zero retain count. You make this happen simply by not releasing it after you create it.

Upvotes: 6

Giuseppe Lanza
Giuseppe Lanza

Reputation: 3699

there is no sense in having a singleton if you will release it. Usually a singleton is created because you want the same object till the app ends. At the end of your app life cycle all memory related to the app is freed.

Use a standard approach, if you need alloc release often. if your singleton takes a lot of memory, you should consider to write it better.

anyway, [[DownloadFirstData shared] release]; will work.

Upvotes: 1

Related Questions