【问题标题】:Memory Management in iPhone?iPhone中的内存管理?
【发布时间】:2011-11-16 06:09:30
【问题描述】:
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {

UILabel *retval = (id)view;

if (!retval) {
    retval= [[UILabel alloc] initWithFrame:CGRectMake(0.0f, 0.0f, [pickerView rowSizeForComponent:component].width, [pickerView rowSizeForComponent:component].height)];
}

NSDictionary *destination = [appDelegate.destinations objectAtIndex:row];
retval.text = [destination objectForKey:@"name"];
retval.font = [UIFont systemFontOfSize:18];
return retval;
}

看方法,在XCode中做产品>分析后,我会在行号得到以下警告

return retval;

Potential leak of an object allocated on line 213 and stored into 'retval'

让我知道,这是什么,我将如何发布,

请编辑此代码,并解释一下您在其中做了哪些更改, 谢谢

【问题讨论】:

  • 像这样自动释放 retval... retval= [[[UILabel alloc] initWithFrame:CGRectMake(0.0f, 0.0f, [pickerView rowSizeForComponent:component].width, [pickerView rowSizeForComponent:component]。高度)]自动释放];

标签: iphone memory-management


【解决方案1】:

retval 是您分配但从不释放的 UILabel。通常,您会将其创建为

retval= [[[UILabel alloc] initWithFrame:CGRectMake(0.0f, 0.0f, [pickerView rowSizeForComponent:component].width, [pickerView rowSizeForComponent:component].height)] autorelease];

并在调用方法中,将其添加到视图或其他内容中。

【讨论】:

    【解决方案2】:

    当您分配标签时,请将其保持在自动释放模式,因为您需要在某处释放 RETVAL。您还没有发布它,因此发现了泄漏。

    retval= [[[UILabel alloc] initWithFrame:CGRectMake(0.0f, 0.0f, [pickerView rowSizeForComponent:component].width, [pickerView rowSizeForComponent:component].height)]autorelease];
    
    猜你喜欢
    • 2011-07-25
    • 2011-04-10
    • 2011-10-10
    • 2010-10-28
    相关资源
    最近更新 更多