iphone - 引用计数的不正确减少

标签 iphone objective-c ios memory-management

我有以下问题:在一个执行流程中我使用 alloc,而在另一个流程中,不需要 alloc。 在 if 语句的末尾,无论如何,我释放了对象。 当我执行“构建和分析”时,出现错误:“调用者不拥有对象引用计数的不正确减少”。

如何解决?

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];

最佳答案

您应该保留第二种情况下的图像:

image = [[UIImage imageNamed:@"dd"] retain];

这样,从您的角度来看,两种可能的条件退出都会有一个引用计数为 1 的对象。

否则,您正在尝试释放一个已经自动释放的对象!

关于iphone - 引用计数的不正确减少,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2993521/

相关文章:

iphone - UIImagePickerController - 设置最大视频持续时间

ios - Xcode 警告 : "no rule to process file" and "Directory not found"

objective-c - 把很长的 NSString 剪掉一部分

ios - 在 iOS 10+ 中,有什么方法可以可靠地唤醒应用程序

ios - 如何在后台 iOS 应用程序时收听日历事件?

iphone - 检查 iVar 的名称是否与 NSDictionary 键相关

iphone - *.xib、*.m 和 *.h 文件如何关联?

ios - 添加额外控件时的 UITableViewController 或 UIViewController

ios - 使用签名请求从 React Native (iOS) 直接发布到 AWS S3

iphone - 无限循环添加 subview