2011-05-17 71 views
0

長時間偵聽器,第一次調用者。ObjC對象更改爲隨機對象:內存問題

我有一個基本的內存問題,我不明白,我相信你們中的任何一個人都會在第二個問題中看到。我在玩耍,試圖學習使用UIWebViews的各種方式,從URL獲取字符串等等。具體來說,我試圖從另一個URL中獲取一個網址。換句話說,我已經上傳了一個包含URL的網頁到網頁。該頁面的地址被編碼到應用程序中,爲應用程序提供了一個「掛鉤」 - 我可以隨時更改該頁面的內容並嚮應用程序發送新URL。合理?

那麼...檢索URL?沒問題。將它傳遞給一個字符串供以後使用 - 沒問題。但是,當我設置一個輕敲手勢識別器(應該接受該字符串),將其轉換回NSURL並在Safari中打開它時,我會遇到運行時崩潰。一個NSLog調用告訴我,有問題的字符串不斷分配給各種隨機事物。

我的代碼的相關位跟在後面。我相信你們中的一些人會告訴我有很多更好的方式去做我想做的事 - 這當然是受歡迎的。但我也很想知道我在做這個特定實現時做了什麼錯誤,因爲我確定這是我想要糾正的一個基本誤解。

在此先感謝。 (和抱歉的代碼塊的格式 - 還沒有完全得到了掛在這裏張貼的!)

#import "Messing_With_Web_ViewsViewController.h" 

    @implementation Messing_With_Web_ViewsViewController 

    @synthesize tapView; 

    NSString *finalURL; 


    - (void)viewDidLoad { 
     [super viewDidLoad]; 

NSString *firstString = @"http://www.my_web_address.html"; 
//Of course, I have the correct address here. 

NSURL *firstUrl = [NSURL URLWithString:firstString]; 

NSError * error; 
finalURL = [NSString stringWithContentsOfURL:firstUrl 
    encoding:NSASCIIStringEncoding error:&error]; 
if (finalURL) 
{ 

    NSLog(@"Text=%@", finalURL); 
    //everything fine up to here; console prints the correct 
      contents of "my web address" 
} 
else 
{ 
    NSLog(@"Error = %@", error); 
} 


    //Taps 
    UITapGestureRecognizer *tapRecognizer; 
    tapRecognizer=[[UITapGestureRecognizer alloc] 
       initWithTarget:self 
       action:@selector(foundTap:)]; 
    tapRecognizer.numberOfTapsRequired=1; 
tapRecognizer.numberOfTouchesRequired=1; 
    [tapView addGestureRecognizer:tapRecognizer]; 
    [tapRecognizer release]; 

    } 


    - (void)foundTap:(UITapGestureRecognizer *)recognizer { 

NSLog(@"Trying to load %@", finalURL); 
//at this point the app either crashes, or the console shows a random memory object 
[[UIApplication sharedApplication] openURL:[NSURL URLWithString: finalURL]]; 
    } 


    - (void)didReceiveMemoryWarning { 

    [super didReceiveMemoryWarning]; 
    } 

    - (void)viewDidUnload { 

    } 


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

@end

回答

4

finalURL = [NSString stringWithContentsOfURL:firstUrl encoding:NSASCIIStringEncoding error:&error];

上面的行創建的NSString的一個實例你不擁有(因爲你沒有調用其名稱包括'新','分配''保留'或'複製'的方法)。那finalURL因此最終會被銷燬時,它不再需要。當您的-foundTap:方法運行時,finalURL已被釋放,並且您只是引用它曾經存在的內存位置,而現在可能包含一些其他對象或隨機數據。

再次閱讀內存管理指南,並學習運行靜態分析器,應該指出這樣的錯誤。

+0

非常感謝,約拿。 – 2011-05-17 03:43:27