Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatic Reference Counting Issue: Assigning retained object to unsafe_unretained variable; object will be released after assignment

I'm getting this warning

"Automatic Reference Counting Issue: Assigning retained object to unsafe_unretained variable; object will be released after assignment"

Here is the code

.h

@interface myObject : NSObject
{
}

@property (assign) id progressEnergy;

@end

.m

@implementation myObject

@synthesize progressEnergy;

-(id)init
{
    if ( ( self = [super init] ) )
    {
        progressEnergy = [[progress alloc] init]; //warning appear on this line
    }

    return self;
}

@end

I have already tried

@property (assign) progress* progressEnergy;

but no luck

Can you please help me figure out what is wrong?

like image 726
zeroonnet Avatar asked Mar 05 '12 22:03

zeroonnet


2 Answers

Well it's warning you that you're assigning a value that's about to get released at the end of the enclosing scope, which happens to be the next line. So this is what your init will look like after ARC adds in its magic:

-(id)init
{
    if ( ( self = [super init] ) )
    {
        progressEnergy = [[progress alloc] init];
        [progressEnergy release]; ///< Release progressEnergy since we've hit the end of the scope we created it in
    }

    return self;
}

So your progressEnergy is now extremely likely (although not necessarily) to be a dangling pointer.

Change the definition of the property from assign to strong:

@property (strong) progress* progressEnergy;

In that case, your init method will look like:

-(id)init
{
    if ( ( self = [super init] ) )
    {
        progressEnergy = [[progress alloc] init];
        [progressEnergy retain]; ///< Since it's a strong property
        [progressEnergy release]; ///< Release progressEnergy since we've hit the end of the scope we created it in
    }

    return self;
}

In actual fact, it calls objc_storeStrong instead of calling retain like I've shown, but essentially it boils down to a retain in this case.

like image 99
mattjgalloway Avatar answered Oct 21 '22 09:10

mattjgalloway


Change

@property (assign) progress* progressEnergy;

to

@property (strong) progress* progressEnergy;

so your myObject retains the progress object.

like image 29
Wevah Avatar answered Oct 21 '22 09:10

Wevah