【问题标题】:Incorrect decrement warning from Xcode from my class method我的类方法中来自 Xcode 的错误递减警告
【发布时间】:2011-12-05 14:49:52
【问题描述】:

我创建了一个类来在 1 行中处理我的 UILabel,而不是通过执行来处理 4-5 个...

+(UILabel*)BeautifyLabel:(UILabel *)label withText:(NSString *)message withFont:(NSString *)font andSize:(float)size andColor:(UIColor *)theColor{
    label.backgroundColor = [UIColor clearColor];
    label.textColor = theColor;
    label.font = [UIFont fontWithName:font size:size];
    label.text = message;
    return label;
}

要称呼它,我愿意

UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake....];
label = [CommonMethods BeautifyLabel:label withText:@"hi" withFont:@"Helvetica" andSize:13 andColor:[UIColor whiteColor]];
[self.view addSubview label];
[label release];

分析器可能不喜欢我将标签传递给我的 CommomMethods 类的部分,但由于我正在初始化并释放当前控制器中的标签,而 CommonMethods 类不做任何与内存相关的事情,这是安全吧?

另外,这会导致 Apple 拒绝我的应用吗?

谢谢

【问题讨论】:

  • 苹果为什么要拒​​绝?
  • 分析仪错误的文本是什么?它抱怨什么?
  • “调用者此时不拥有的对象的引用计数减少错误”,并在[label release] 行显示警告。

标签: iphone cocoa-touch memory-management


【解决方案1】:

您的 BeautifyLabel 方法不应返回标签指针。这可能是分析器所抱怨的(但很高兴看到分析器错误的文本)。

分析器假设 BeautifyLabel 方法正在返回标签的一个新实例,然后覆盖标签变量中的那个实例,从而导致被覆盖实例的内存泄漏(以及返回的实例的过度释放)。

【讨论】:

  • 分析器中的文本是“调用者此时不拥有的对象的引用计数不正确递减”。但是由于我在我的类方法中进行了任何初始化、复制、保留或释放,所以没有泄漏或过度释放,对吧?
  • @AndrewPark - 静态分析器实际上并没有运行代码,因此它并不真正知道最终是否一切正常 - 它会检查您是否遵循指南,以及代码绝对没有。
  • 啊,谢谢。我更改了类方法,以便在其中初始化标签,然后在返回之前自动释放它。
【解决方案2】:

在代码中:

UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake....];
label = [CommonMethods BeautifyLabel:label withText:@"hi" withFont:@"Helvetica" andSize:13 andColor:[UIColor whiteColor]];

label 分配在第一行,第二行 labelreplaed 调用 BeautifyLabel 或者分析器认为是这样,不知道在 @987654325 中做了什么@。它不能假设您返回的是同一个对象。

要么不做作业:

[CommonMethods BeautifyLabel:label withText:@"hi" withFont:@"Helvetica" andSize:13 andColor:[UIColor whiteColor]];

或使用不同的标签指针名称:

UILabel *labelTemp = [[UILabel alloc] initWithFrame:CGRectMake....];
label = [CommonMethods BeautifyLabel:labelTemp withText:@"hi" withFont:@"Helvetica" andSize:13 andColor:[UIColor whiteColor]];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-17
    • 2013-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-25
    相关资源
    最近更新 更多