Srinivas
Srinivas

Reputation: 1059

singleton class memory leakage

I set up a singleton following the instructions at this tutorial, but when I analyze it I see the following memory leaks:

enter image description here

How do I rectify this memory leakage in my singleton class?

Upvotes: 3

Views: 808

Answers (4)

Girish Kolari
Girish Kolari

Reputation: 2515

[[self alloc] init]; - is not assigned to the object

Upvotes: 0

Fran Sevillano
Fran Sevillano

Reputation: 8163

I think that whoever that wrote that tutorial didn't write this right:

 [[self alloc] init];

Instead, it sould be:

_sharedMySingleton = [[MySingleton alloc]init];

I hope it helps

Upvotes: 6

Jake
Jake

Reputation: 3973

You do not assign the allocation to a variable. Change it to this:

+(MySingleton*)sharedMySingleton
{
    @synchronized(self)
    {
      if (!_sharedMySingleton)
           _sharedMySingleton = [[self alloc] init];
    }

    return _sharedMySingleton;
}

EDIT my typing was too slow, others have already replied :)

Upvotes: 5

Dave
Dave

Reputation: 3448

It looks like when you return _sharedMySingleton, it will still be nil. And hence allocated the next time, too. You should try setting it when the alloc is done.

Upvotes: 0

Related Questions