2012-07-05 76 views
1

首先,我非常感謝您的幫助。AppDelegate的屬性意外設置爲空

那麼,我在兩個視圖中使用了三個共同的NSString對象。這些視圖被嵌入式NavigationController所困擾,我的意思是我開始用SingleView編程。

在AppDelegate.h,我寫

@property (weak, nonatomic) NSString *crntURL; 

@property (weak, nonatomic) NSString *crntTitle; 

@property (weak, nonatomic) NSString *crntHTML; 

進行委派。

而在第一種觀點,我有一個網頁視圖,寫

-(void)webViewDidFinishLoad:(UIWebView *)webView 
{ 
    AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate]; 
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO; 
    NSString *url = [[NSString alloc] initWithString:[myWebView  stringByEvaluatingJavaScriptFromString:@"document.URL"]]; 
    NSString *title = [[NSString alloc] initWithString:[myWebView stringByEvaluatingJavaScriptFromString:@"document.title"]]; 
    NSString *html = [[NSString alloc] initWithString:[myWebView stringByEvaluatingJavaScriptFromString:@"document.all[0].outerHTML"]]; 
    appDelegate.crntTitle = nil; 
    appDelegate.crntTitle = [[NSString alloc] initWithString:title]; 
    appDelegate.crntHTML = nil; 
    appDelegate.crntHTML = [[NSString alloc] initWithString:html]; 
    appDelegate.crntURL = nil; 
    appDelegate.crntURL = [[NSString alloc] initWithString:url]; 
} 

在這裏,當我把NSLog的,預期的HTML源代碼被傾倒。

而在第二視圖(的UIViewController的一個子類),我寫

- (void)viewDidLoad 
{ 
    // Do any additional setup after loading the view. 
    AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate]; 
    sourceHTML.text = appDelegate.crntHTML; 
    NSLog(@"%@", appDelegate.crntHTML); 
    NSLog(@"%@", appDelegate.crntURL); 
    NSLog(@"%@", appDelegate.crntTitle); 
    [super viewDidLoad]; 
} 

只有crntHTML意外設置爲null而crntURL和crntTitle保留值。

你有什麼想法嗎?

預先感謝您。

Masaru

+0

爲什麼所有以'[的NSString initWithString]'電話?前幾個可能是好的,但最後三個是完全多餘的。 – Mac

+0

前幾個也完全是多餘的。局部變量隱含地是'__strong',所以'alloc' /'initWithString'業務不需要做引用計數幫助。如果你的意思是確保你的一個變量持有一個單獨的字符串副本,最好使用'copy'。 – rickster

回答

1

您已聲明您在應用程序委託中的屬性較弱。 使用ARC時,如果沒有強引用,則會釋放對象並將其設置爲零。

我可以想象你正在引用來自第一個視圖控制器的標題和URL變量,但是HTML變量僅在第二個視圖控制器中被引用。一旦準備好在第二個控制器中顯示HTML,它已經被釋放,因爲應用程序委託並沒有保留它。

嘗試在應用程序的委託更改屬性聲明強:

@property (strong, nonatomic) NSString *crntURL; 
@property (strong, nonatomic) NSString *crntTitle; 
@property (strong, nonatomic) NSString *crntHTML; 
+0

我很抱歉遲到。 謝謝你的解釋。 –