11

我收到此警告

“自动引用计数问题:将保留对象分配给 unsafe_unretained 变量;分配后对象将被释放”

这是代码

。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

我已经试过了

@property (assign) progress* progressEnergy;

但没有运气

你能帮我找出问题所在吗?

4

2 回答 2

28

改变

@property (assign) progress* progressEnergy;

@property (strong) progress* progressEnergy;

所以你myObject保留了progress对象。

于 2012-03-05T22:45:35.923 回答
10

好吧,它警告您,您正在分配一个即将在封闭范围末尾释放的值,这恰好是下一行。所以这就是你init在 ARC 加入它的魔力之后的样子:

-(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;
}

因此,您progressEnergy现在极有可能(尽管不一定)成为悬空指针。

将属性的定义从 更改assignstrong

@property (strong) progress* progressEnergy;

在这种情况下,您的init方法将如下所示:

-(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;
}

实际上,它调用objc_storeStrong而不是像我展示的那样调用,但在这种情况下retain,它本质上归结为 a 。retain

于 2012-03-05T22:47:06.030 回答