idd*_*ber 2 iphone memory-management objective-c ios
我有以下问题:在一个执行流程中我使用alloc,而在另一个流程中,不需要alloc.在if语句结束时,无论如何,我都会释放该对象.当我'build and Analize'时,我收到一个错误:'对象的引用计数的不正确的减少不归调用者所有'.
怎么解决?
UIImage *image;
int RandomIndex = arc4random() % 10;
if (RandomIndex<5)
{
image = [[UIImage alloc] initWithContentsOfFile:@"dd"];
}
else
{
image = [UIImage imageNamed:@"dd"];
}
UIImageView *imageLabel =[[UIImageView alloc] initWithImage:image];
[image release];
[imageLabel release];
Run Code Online (Sandbox Code Playgroud)
Chr*_*per 10
您应该retain在第二个条件下的图像:
image = [[UIImage imageNamed:@"dd"] retain];
Run Code Online (Sandbox Code Playgroud)
这样,从您的角度来看,条件之外的两个可能出口都将具有引用计数为1的对象.
否则,你正在尝试release一个已经autoreleased的对象!
你可以做别人的建议,或者:
if (RandomIndex<5)
{
image = [UIImage imageWithContentsOfFile:@"dd"];
}
else
{
image = [UIImage imageNamed:@"dd"];
}
UIImageView *imageLabel =[[UIImageView alloc] initWithImage:image];
...
[imageLabel release];
Run Code Online (Sandbox Code Playgroud)
这样,在这两种情况下,您都会获得一个自动释放的对象image,然后您不需要自行释放.