2013-10-12 57 views
2

我有一個小的問題,ARC和dealloc的BaseViewController類在循環內實例化後被調用,我不知道爲什麼。我想要做的是基本上將所有的基本視圖控制器存儲在一個數組上。爲什麼在實例化之後立即調用dealloc?

@interface CategoriesContainerViewController() 
    @property (nonatomic, strong) IBOutlet UIScrollView* scrollView; 
    @property (nonatomic, strong) NSMutableArray* categoriesViews; 
@end 

- (void)viewDidLoad { 

    [super viewDidLoad]; 

    // Get the categories from a plist 
    NSString* path = [[NSBundle mainBundle] pathForResource:@"categories" ofType:@"plist"]; 
    NSDictionary* dict = [[NSDictionary alloc] initWithContentsOfFile:path]; 
    NSMutableArray* categories = [dict objectForKey:@"Categories"]; 
    NSLog(@"%i", [categories count]); 

    // Setup the scrollview 
    _scrollView.delegate = self; 
    _scrollView.directionalLockEnabled = YES; 
    _scrollView.alwaysBounceVertical = YES; 
    _scrollView.scrollEnabled = YES; 

    CGRect screenRect = [[UIScreen mainScreen] bounds]; 

    // Loop through the categories and create a BaseViewController for each one and 
    // store it in an array 
    for (int i = 0; i < [categories count]; i++) { 

    BaseViewController* categoryView = [[BaseViewController alloc] 
             initWithCategory:[categories objectAtIndex:i]]; 

    CGRect frame = categoryView.view.frame; 
    frame.origin.y = screenRect.size.height * i; 
    categoryView.view.frame = frame; 

    [_scrollView addSubview:categoryView.view]; 
    [_categoriesViews addObject:categoryView]; 
    } 

} 
+2

你曾經實例化'categoriesViews'嗎? – Wain

+0

你是對的@很好!它現在按預期工作。 – 72lions

回答

4

你被保持到一個視圖控制器的視圖的引用犯一個共同的錯誤初學者,但不是視圖控制器本身。

您在本地變量categoryView中創建一個BaseViewController對象。這是一個強有力的參考,所以對象保持在周圍。然後循環重複,並且您創建一個新的BaseViewController,替換categoryView中的舊值。當你這樣做時,不再有任何強大的引用到categoryView中的前一個BaseViewController,因此它被取消分配。

如果您希望BaseViewController繼續存在,您需要在某處保留強引用。

除此之外,你正在打破iOS開發的另一個規則。除非您使用在iOS 5中添加並在iOS 6中擴展的父/子視圖控制器支持,否則絕不應該將一個視圖控制器的視圖放在另一個視圖控制器內。文檔說不這樣做。

從屏幕上的多個視圖控制器混合視圖將導致您無法解決問題。你需要做很多的管家工作才能完成工作,並不是所有的家務管理都有記錄。它的可能,但它會花你幾個星期來消除錯誤,如果你有能力。此外,由於你正在做的事情,蘋果明確表示不做,負擔是讓你的工作正常,並有一個很大的風險,新的iOS版本將打破你的應用程序。

+0

非常感謝您指出這些事情!我很感激!我試圖找出更多關於父/子視圖控制器的信息,但是我沒有成功。你能指出一些教程,文件等嗎? – 72lions

0

初始化上面的for循環的BaseViewController,然後將數組值存儲在BaseViewController的對象內。因爲每次它分配和初始化。因此將前一個對象設置爲零。因此問題導致被釋放。

相關問題