2012-06-18 62 views
2

我有一個教程應用程序,演示如何使用UINavigationController。大多數應用程序的作品正確倖存的ios內存警告

當我模擬內存警告時,它丟失了一些數據。我在UINavigationController中有兩個UIViewController。首先在UIViewController的視圖上有一個UIButton,當用戶觸摸UIButton時,第二個UIViewController被創建,並且首先推動導航堆棧UIViewController。我通過NSNotificationCenter將數據從第二個UIViewController傳遞到第一個UIViewController

有了這種方法,應用程序工作正常,但如果我模擬內存警告時,第二個UIViewController的視圖是可見的沒有回傳。那麼我怎麼能在這種情況下生存。

+0

我們可以看到相關的代碼? – 2012-06-18 12:50:32

回答

0

當內存警告被觸發時,應用程序會試圖擺脫所有不再需要的對象。這可能會從第一個UIViewController中刪除偵聽器。

NSNotificationCenter的問題在於,沒有簡單的方法來檢查監聽器是否處於活動狀態。

我不知道這種情況是否適合使用NSNotification設置。很容易失去對什麼視圖控制器發送什麼消息的控制。

也許這個設置更容易(可能內存更安全)。它保持到第一的UIViewController對象

// 
// SecondViewController.h 
// test 
// 
// 

#import <UIKit/UIKit.h> 
#import "ViewController.h" 

@interface SecondViewController : UIViewController 

@property(nonatomic, retain) ViewController *parentViewController; 

@end 

與.m文件

// 
// SecondViewController.m 
// test 
// 
// 

#import "SecondViewController.h" 

@interface SecondViewController() 
    -(IBAction)buttonPressed:(id)sender; 
@end 

@implementation SecondViewController 

@synthesize parentViewController; 

-(IBAction)buttonPressed:(id)sender { 
    parentViewController.yourObject = @"your value"; 
} 

-(void)dealloc { 
    [parentViewController release]; 
    [super dealloc]; 
} 

當按下第二視圖 - 控制做到這一點參考:

SecondViewController *vc = [[SecondViewController alloc] initWithNibName:@"SecondViewController" bundle:nil]; 
    vc.parentViewController = self; 
    [self.navigationController pushViewController:vc animated:YES]; 
[vc release]; 
+0

謝謝你的回答。但我認爲保持視圖控制器分離(讓他們不要直接互相談話)是更好的設計。我想我會創建保持數據更改的獨立模型類。 – fyodor