【问题标题】:Release NSArray assigned to UIBar释放分配给 UIBar 的 NSArray
【发布时间】:2011-08-30 08:35:51
【问题描述】:

在我的应用程序中,我想制作数组,添加到工具栏,然后释放它。但是,当我发布它时,我的应用程序崩溃了。为什么这样...?怎么做才能省略它?

UIImage *button1Image = [UIImage imageNamed:@"button1Image.png"];
cameraToolbar = [[UIToolbar alloc] init]; //declared in .h
UIBarButtonItem *button1 = [[ UIBarButtonItem alloc ] initWithTitle: @"qwerty" style: UIBarButtonItemStyleBordered target: self action: @selector(doAction)];
[button1 setImage:button1Image];
//same method to add flexItem and button2Image

NSArray *items = [NSArray arrayWithObjects: button1, flexItem, button2, nil];
[cameraToolbar setItems:items animated:NO];
self.view = cameraToolbar;

[items release]; // here it crashes, why? How to fix?
[button1 release];
[button2 release];
[flexItem release];
[button1Image release]; // here i get "Incorrect decrement of the reference count 
//of an object that is not owned at this point by the caller"
[button2Image release];

【问题讨论】:

    标签: ios objective-c memory-management nsarray


    【解决方案1】:

    [NSArray arrayWithObjects:] 是一个类方法,它返回一个数组,该数组是自动释放的对象。所以你不应该释放它。 p>

    如果你使用 alloc,copy,retain 来创建对象,那么只有你有责任释放它们。

    NSArray *items=[[NSArray alloc]initWithObjects:button1, flexItem, button2, nil];
    
    
    ............
    
    
    
    [items release];
    

    对 button1Image 对象像这样。小心

    【讨论】:

    • 太棒了!但是释放 buttonImages 怎么办?我在分析时收到此警告..
    • 任何对象的任何地方都可以采用这种行为。
    • 如果你使用 alloc,retain,copy 那么你必须释放它。在 ios5 ARC 将帮助我们。直到现在我们必须手动完成。
    • 按钮图像也是自动释放的。以类名开头的便捷类方法一般返回自动释放的对象。
    【解决方案2】:

    button1Image 被分配了一个自动释放的对象,因此不应发送释放消息。内存管理基于对象引用计数,当计数为零时,内存将被释放。释放消息将引用计数减一。

    【讨论】:

      猜你喜欢
      • 2011-09-06
      • 1970-01-01
      • 2016-03-28
      • 2011-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多