2010-08-23 2 views
5

내가 개발중인 응용 프로그램은 응용 프로그램 주위에 중앙 집중화 된 일부 활동에 대한 내장 된 웹 탐색 환경을 허용하는 데 사용되는 여러 WebViews를 유지합니다. 내가 가지고있는 문제는 여러 시간 동안 열어서 많은 사용 후에보기가 메모리를 구축하기 시작한다는 것입니다. Objective-C의 메모리 관리에 대한 나의 이해는 한 번, 객체가 완전히 해제 (count = 0 유지)되고 전체적으로 애플리케이션이 사용하는 메모리 양이 할당 취소된다는 것입니다. 이것은 내 상황에 적용되지 않는 것 같습니다.WebView 메모리 관리

[webviewObject release]; 
webviewObject = nil; 

webviewObject = [[self createNewViewWithName:name] retain]; 

위 코드는 내가 사용하고있는 코드입니다. 나는 메모리를 풀어보고 새로운 인스턴스를 만들지는 않았지만 운이 없다. 메모리 사용량은 계속해서 증가하고 있으며, Instruments에 따르면 객체는 완전히 해제됩니다. 내가 놓친 게 있니? 응용 프로그램에서 어떻게 캐싱을 할 수 있습니까?

+1

"createNewViewWithName :"이 어떻게 생겼는지 보여줄 필요가 있다고 생각합니다. – Kalle

+0

예, 어떻게 든 유지하는 것 같습니다. createNewViewWithName이 자동 렌더링 된 객체를 반환하는지 확실하지 않습니다. – vodkhang

답변

1

내 앱 중 하나에서 웹보기에서 비슷한 문제가있었습니다. 아이폰 SDK에서 웹보기로 메모리 누수가있는 것 같습니다. 웹보기에 큰 텍스트가 있었을 때 내 앱이 다운되고 다른 문제가 발생했습니다. This code은 메모리 누수를 방지하는 데 도움이되었습니다. 나는 그것이 당신을 위해 일하기를 바랍니다.

은 다음 링크의 지침입니다 :있는 UIWebView 관련

방지 메모리 누수가 어려울 수 있습니다. 주제에 관한 Apple의 문서는 드물고 단순하지 않고 입니다. 왜냐하면 UIWebView는 내부에 사용되는 많은 기본 클래스가있는 복잡한 짐승이기 때문입니다. 이 Objective-C 카테고리는 다양한 웹 블로그에서 의 아이디어와 이론 (과학이 아닌 마술이라고 생각합니다)을 수집하여 주제에 대한 토론을 수집합니다. more Objective-C 메모리 관리 아이디어, WIJL : IOS 메모리 관리를 확인하십시오. 범주를 사용하면 간단하다

다운로드 코드 :있는 UIWebView + Clean.zip

  1. 이 프로젝트에있는 UIWebView + Clean.h와하는 .m 파일을 추가합니다. .
[self.webView cleanForDealloc]; 
self.webView = nil; 

이것은 UIWebView+Clean.h :

/* 

    UIWebView+Clean.h 

    A simple category that performs recommended UIWebView clean before dealloc 

    Created by Jason Baker ([email protected]) for TumbleOn on 3/18/12. 

    Copyright (c) 2012, Pocket Sized Giraffe, LLC 
    All rights reserved. 

    Redistribution and use in source and binary forms, with or without 
    modification, are permitted provided that the following conditions are met: 

    1. Redistributions of source code must retain the above copyright notice, this 
    list of conditions and the following disclaimer. 
    2. Redistributions in binary form must reproduce the above copyright notice, 
    this list of conditions and the following disclaimer in the documentation 
    and/or other materials provided with the distribution. 

    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 
    ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 
    DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 
    ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 
    (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 
    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 
    ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 
    SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 

    The views and conclusions contained in the software and documentation are those 
    of the authors and should not be interpreted as representing official policies, 
    either expressed or implied. 

*/ 

#import <Foundation/Foundation.h> 

@interface UIWebView (clean) 

// performs various cleanup activities recommended for UIWebView before dealloc. 
// see comments in implementation for usage examples 
- (void) cleanForDealloc; 

@end 
당신이 범주를 사용하고자하는 모든 파일에
  • 가져 오기 UIWebView+Clean.h
  • 당신이있는 UIWebView의 할당을 해제하려는 어디서나 cleanForDealloc 방법을 사용

    그리고 이것은 UIWebView+Clean.m :

    입니다.
    /* 
    
    UIWebView+Clean.h 
    
    A simple category that performs recommended UIWebView clean before dealloc 
    
    Created by Jason Baker ([email protected]) for TumbleOn on 3/18/12. 
    
    Copyright (c) 2012, Pocket Sized Giraffe, LLC 
    All rights reserved. 
    
    Redistribution and use in source and binary forms, with or without 
    modification, are permitted provided that the following conditions are met: 
    
    1. Redistributions of source code must retain the above copyright notice, this 
    list of conditions and the following disclaimer. 
    2. Redistributions in binary form must reproduce the above copyright notice, 
    this list of conditions and the following disclaimer in the documentation 
    and/or other materials provided with the distribution. 
    
    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 
    ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 
    DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 
    ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 
    (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 
    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 
    ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 
    SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
    
    The views and conclusions contained in the software and documentation are those 
    of the authors and should not be interpreted as representing official policies, 
    either expressed or implied. 
    
    */ 
    
    #import "UIWebView+Clean.h" 
    
    @implementation UIWebView (clean) 
    
    /* 
    
    Using this Category is easy, simply add this to the top of your file where 
    you have a UIWebView: 
    
    #import "UIWebView+Clean.h" 
    
    Then, any time you want to throw away or deallocate a UIWebView instance, do 
    the following before you throw it away: 
    
    [self.webView cleanForDealloc]; 
    self.webView = nil; 
    
    If you still have leak issues, read the notes at the bottom of this class, 
    they may help you. 
    
    */ 
    
    
    - (void) cleanForDealloc 
    { 
        /* 
    
        There are several theories and rumors about UIWebView memory leaks, and how 
        to properly handle cleaning a UIWebView instance up before deallocation. This 
        method implements several of those recommendations. 
    
        #1: Various developers believe UIWebView may not properly throw away child 
        objects & views without forcing the UIWebView to load empty content before 
        dealloc. 
    
        Source: http://stackoverflow.com/questions/648396/does-uiwebview-leak-memory 
    
        */   
        [self loadHTMLString:@"" baseURL:nil]; 
    
        /* 
    
        #2: Others claim that UIWebView's will leak if they are loading content 
        during dealloc. 
    
        Source: http://stackoverflow.com/questions/6124020/uiwebview-leaking 
    
        */ 
        [self stopLoading]; 
    
        /* 
    
        #3: Apple recommends setting the delegate to nil before deallocation: 
        "Important: Before releasing an instance of UIWebView for which you have set 
        a delegate, you must first set the UIWebView delegate property to nil before 
        disposing of the UIWebView instance. This can be done, for example, in the 
        dealloc method where you dispose of the UIWebView." 
    
        Source: UIWebViewDelegate class reference  
    
        */ 
        self.delegate = nil; 
    
    
        /* 
    
        #4: If you're creating multiple child views for any given view, and you're 
        trying to deallocate an old child, that child is pointed to by the parent 
        view, and won't actually deallocate until that parent view dissapears. This 
        call below ensures that you are not creating many child views that will hang 
        around until the parent view is deallocated. 
        */ 
    
        [self removeFromSuperview]; 
    
        /* 
    
        Further Help with UIWebView leak problems: 
    
        #1: Consider implementing the following in your UIWebViewDelegate: 
    
        - (void) webViewDidFinishLoad:(UIWebView *)webView 
        { 
         //source: http://blog.techno-barje.fr/post/2010/10/04/UIWebView-secrets-part1-memory-leaks-on-xmlhttprequest/ 
         [[NSUserDefaults standardUserDefaults] setInteger:0 forKey:@"WebKitCacheModelPreferenceKey"]; 
        } 
    
        #2: If you can, avoid returning NO in your UIWebViewDelegate here: 
    
        - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType 
        { 
         //this source says don't do this: http://stackoverflow.com/questions/6421813/lots-of-uiwebview-memory-leaks 
         //return NO; 
         return YES; 
        } 
    
        #3: Some leaks appear to be fixed in IOS 4.1 
        Source: http://stackoverflow.com/questions/3857519/memory-leak-while-using-uiwebview-load-request-in-ios4-0 
    
        #4: When you create your UIWebImageView, disable link detection if possible:   
    
        webView.dataDetectorTypes = UIDataDetectorTypeNone; 
    
        (This is also the "Detect Links" checkbox on a UIWebView in Interfacte Builder.) 
    
        Sources: 
        http://www.iphonedevsdk.com/forum/iphone-sdk-development/46260-how-free-memory-after-uiwebview.html 
        http://www.iphonedevsdk.com/forum/iphone-sdk-development/29795-uiwebview-how-do-i-stop-detecting-links.html 
        http://blog.techno-barje.fr/post/2010/10/04/UIWebView-secrets-part2-leaks-on-release/ 
    
        #5: Consider cleaning the NSURLCache every so often: 
    
        [[NSURLCache sharedURLCache] removeAllCachedResponses]; 
        [[NSURLCache sharedURLCache] setDiskCapacity:0]; 
        [[NSURLCache sharedURLCache] setMemoryCapacity:0]; 
    
        Source: http://blog.techno-barje.fr/post/2010/10/04/UIWebView-secrets-part2-leaks-on-release/ 
    
        Be careful with this, as it may kill cache objects for currently executing URL 
        requests for your application, if you can't cleanly clear the whole cache in 
        your app in some place where you expect zero URLRequest to be executing, use 
        the following instead after you are done with each request (note that you won't 
        be able to do this w/ UIWebView's internal request objects..): 
    
        [[NSURLCache sharedURLCache] removeCachedResponseForRequest:request]; 
    
        Source: http://stackoverflow.com/questions/6542114/clearing-a-webviews-cache-for-local-files 
    
        */ 
    } 
    
    @end