UIWebView使用中的記憶體相關問題

來源:互聯網
上載者:User

標籤:blog   http   使用   os   art   for   

本文轉載至: http://blog.csdn.net/musou_ldns/article/details/7675589 applicationios5webkit測試cacheios

在iOS5平台開發應用的過程中,發現使用UIWebView通過NSURLRequest載入網頁後,即使UIWebView所在畫面關閉,仍然有記憶體無法釋放。 

結果就是,通過UIWebVIew訪問的頁面越多,應用的記憶體佔用也越多,從而有導致記憶體警告而造成程式退出的可能。 

通過調查網上的相關資料,發現UIWebVIew的記憶體問題由來已久,在iOS4時代就已經存在。 

stackflow有大量的相關提問和解決辦法,例如清空cache: 

 

 

- (void)webViewDidFinishLoad:(UIWebView *)webView {

 

    // new for memory cleaning 

    [[NSUserDefaults standardUserDefaults] setInteger:0 forKey:@"WebKitCacheModelPreferenceKey"];

    // new for memory cleanup 

    [[NSURLCache sharedURLCache] setMemoryCapacity: 0];

    NSURLCache *sharedCache = [[NSURLCache alloc] initWithMemoryCapacity:0 diskCapacity:0 diskPath:nil];

    [NSURLCache setSharedURLCache:sharedCache];

}

在畫面結束時讓UIWebView載入空白頁面: 

 

[webView loadHTMLString:@"" baseURL:nil];

[webView stopLoading];

[webView setDelegate:nil];

[webView removeFromSuperview];

[[NSURLCache sharedURLCache] removeAllCachedResponses];

但經過實機測試,發現並沒有什麼效果。

網路上大部分開發人員的意見是,目前UIWebView的記憶體問題出在 WebKit裡,開發人員仍舊沒有很好的解決辦法。

隨後發現了另一種變相的解決方式,既然無法阻止記憶體佔用量的持續上升,就把它控制在一定的範圍以內並及時清空。

具體的方式如下:

在UIApplicationDelegate中的

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions方法中添加如下代碼:

int cacheSizeMemory = 4*1024*1024; // 4MB
int cacheSizeDisk = 32*1024*1024; // 32MB
NSURLCache *sharedCache = [[[NSURLCache alloc] initWithMemoryCapacity:cacheSizeMemory diskCapacity:cacheSizeDisk diskPath:@"nsurlcache"] autorelease];
[NSURLCache setSharedURLCache:sharedCache];

同時追加記憶體警告時的處理:

- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application {
    [[NSURLCache sharedURLCache] removeAllCachedResponses];
}

經實機測試,的確會降低系統記憶體的用量,但應用本身的記憶體佔用量沒有大的變化。

以上調查結果,僅供參考。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.