【问题标题】:How to release objects using Product > Analyze in XCode?如何在 XCode 中使用 Product > Analyze 释放对象?
【发布时间】:2011-12-30 03:09:27
【问题描述】:

看到下面的代码,它只是一个方法,我无法理解其中的内存管理问题,请告诉我,下面的代码发生了什么,为什么?

-(IBAction)selectMarina {
NSLog(@"Select Marina");
actionSheet = [[UIActionSheet alloc] initWithTitle:nil 
                                          delegate:nil
                                 cancelButtonTitle:nil
                            destructiveButtonTitle:nil
                                 otherButtonTitles:nil];

[actionSheet setActionSheetStyle:UIActionSheetStyleBlackTranslucent];    
CGRect pickerFrame = CGRectMake(0, 40, 0, 0);
pickerView = [[UIPickerView alloc] initWithFrame:pickerFrame];
pickerView.showsSelectionIndicator = YES;
pickerView.dataSource = self;
pickerView.delegate = self;

[actionSheet addSubview:pickerView];
//[pickerView release];

UISegmentedControl *closeButton = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObject:@"Close"]];
closeButton.momentary = YES; 
closeButton.frame = CGRectMake(260, 7.0f, 50.0f, 30.0f);
closeButton.segmentedControlStyle = UISegmentedControlStyleBar;
closeButton.tintColor = [UIColor blackColor];
[closeButton addTarget:self action:@selector(dismissActionSheet:) forControlEvents:UIControlEventValueChanged];
[actionSheet addSubview:closeButton];
//[closeButton release];

[actionSheet showInView:[[UIApplication sharedApplication] keyWindow]];
[actionSheet setBounds:CGRectMake(0, 0, 320, 485)];
[pickerView selectRow:0 inComponent:0 animated:NO];

}

这里是Potential leak of object allocated on line 112 and stored into close button

它正在在线显示这样的消息

    [actionSheet showInView:[[UIApplication sharedApplication] keyWindow]];

如何在这段代码中进行适当的内存管理,您能否详细指定它

谢谢

【问题讨论】:

    标签: iphone memory-management


    【解决方案1】:

    首先你需要释放实例pickerView和closeButton。

    根据规则,每当你分配一个对象时,一旦它的工作完成就必须释放它。在您的情况下,不需要将两个实例都添加到子视图后,因此必须释放它们。否则它将显示您提到的泄漏。

    如需了解更多信息,请参阅内存指南或快速查看点击http://www.raywenderlich.com/2657/memory-management-in-objective-c-tutorial

    【讨论】:

    • 为什么要发布pickerView?
    • 是全局的,也不是本地的,那你说怎么发布呢?
    • 我错过了这一点。如果实例是全局声明的,则必须在 dealloc 方法中释放。
    • 但是我用两种方法初始化它,然后呢?
    • 没关系。您可以多次初始化 ivar。请记住一件事(分配数 = 释放数)。最后 ivar 的保留计数必须为零。
    猜你喜欢
    • 1970-01-01
    • 2012-01-13
    • 2011-05-13
    • 2019-08-21
    • 1970-01-01
    • 2014-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多