2011-08-31 118 views
0

我想从MainWindow中的UITabBarController中删除所有项目。我可以这样做:从UITabBarController中删除所有项目

self.tabViewController.viewControllers = [NSArray array]; 
self.tabViewController.customizableViewControllers = [NSArray array]; 

但是那里的旧控制器呢?这是更正确的方法吗?

- (void)cleanCurrentTabbar { 
    for (id ctrl in self.tabViewController.customizableViewControllers) { 
     [ctrl release]; 
    } 
    for (id ctrl in self.tabViewController.viewControllers) { 
     [ctrl release]; 
    } 
    self.tabViewController.viewControllers = [NSArray array]; 
    self.tabViewController.customizableViewControllers = [NSArray array]; 
} 
+0

你不需要释放tabbar的viewControllers。如果通过设置一个新值来访问属性.customizableViewControllers/.viewControllers,那么在setter方法中,默认情况下会释放此属性的旧值。因此,将[NSArray数组]设置为新值就足够了。 – TRD

+0

@TRD它发布一个数组...不是吗?我想释放数组中的项目。 – NilColor

+1

但是如果你释放一个数组,所有包含项目的释放消息将被发送,因为数组在添加它们时保留了他的项目,所以数组负责释放,而不是你。 – TRD

回答

0

正如@Parth Bhatt告诉,发布viewControllers项目看起来像个好主意。也许。但在我的情况下,它导致了奇怪的EXC_BAD_ACCESS错误: enter image description here 所以我最终与self.tabViewController.viewControllers = nil;和它的作品就好了。

1

你的第二个选择是更正确的观念明智以及相对于内存管理,因为它使得零之前释放所有分配的资源。

但不是给它一个本身就像[NSArray数组]的自动释放对象的空数组,您可以指定nil

- (void)cleanCurrentTabbar { 
    for (id ctrl in self.tabViewController.customizableViewControllers) { 
     [ctrl release]; 
    } 
    for (id ctrl in self.tabViewController.viewControllers) { 
     [ctrl release]; 
    } 
    self.tabViewController.viewControllers = nil; 
    self.tabViewController.customizableViewControllers = nil; 
} 

另外,作为詹姆斯·韦伯斯特已经在打击评论说:

“你可能会或可能不会需要根据财产viewControllers和customizableViewControllers的类型来释放是”

希望这有助于你。

+0

是啊......无。你当然是对的! – NilColor

+1

小心,您可能不需要释放取决于属性viewControllers和customizableViewControllers –

+0

它是@property(nonatomic,copy)NSArray * viewControllers;' – NilColor

0

这是更清洁的内存方面是的。你应该在完成它们之后释放对象,包括在重新分配之前。

但是,我注意到你正在使用self.tabViewController.viewControllers。该财产是分配还是保留?如果保留,发布将在内部完成。

+0

它是'@property(nonatomic,copy)NSArray * viewControllers;' – NilColor

+0

我知道副本增加了一个对象的保留数,但我不确定它在属性中使用时会减少它。我期待它的确如此,但是你可能想要进一步研究 –

+0

@James Webster:'copy'被使用,所以viewControllers需要被释放。 –