iOS2012. 3. 10. 22:13

출처: http://peepleware.com/home/?mid=Tips_dev&page=3&document_srl=12071

아이폰에서 UIWebView 는 PDF 파일외 MS OFFICE계열의 문서 뷰어, 이미지 파일 뷰어, 음악/동영상 파일 열기 등의 다용도 뷰어로 활용할 수 있습니다.


다만 단점이라면 파일 로딩시 파일을 모조리 다 읽어 들여 큰 파일의 경우 메모리 부족 현상이 올 수 있습니다.

그래서 UIWebView로 여러개의 파일들을 지속적으로 반복해서 읽게 되는 경우 메모리 부족으로 인해 UIViewController의 didReceiveMemoryWarning 메소드가 호출될 때가 많아집니다.


그래서 몇 가지 처리를 통해 약간이나마 메모리 부족 현상을 개선해봤습니다.


우선 앱의 초기화 루틴에서 다음과 같이 처리합니다.


- (void)applicationDidBecomeActive:(UIApplication *)application {

    /*

     Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.

     */


// UIWebView에서 사용될 내부 캐시 영역을 만듭니다. 

// 내부 메모리/디스크를 사용하지 않도록 설정했습니다.

// 설정된 캐시 영역을 공통으로 사용하도록 설정합니다.


// 이 부분의 개선을 통해 더욱 발전시킬 여지가 있습니다.

// 점점 개선한 루틴을 통해 실험해보고, 효과가 있으면 소스를 변경하겠습니다.


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

[NSURLCache setSharedURLCache:sharedCache]; 

[sharedCache release];

// 그외 다른 초기 작업들.

}


UIWebView 에서 파일을 열고 사용하다 필요가 없어졌을 때, 호출할 함수.


- (void)unload

{


// 다른 자원들의 해제 작업들.


// UIWebView에서 사용된 요청들의 결과들 캐시를 삭제합니다.

// 이때 대상 캐시는 앱의 초기 구동시에 만들어둔 바로 그 캐시 영역입니다.


NSURLCache *sharedCache = [NSURLCache sharedURLCache]; 

[sharedCache removeAllCachedResponses];

return;

}


그래도 메모리 부족이 발생했을 때 사용할 메소드.


- (void)didReceiveMemoryWarning 

{

    // Releases the view if it doesn't have a superview.

    [super didReceiveMemoryWarning];

    

    // Release any cached data, images, etc. that aren't in use.

NSURLCache *sharedCache = [NSURLCache sharedURLCache]; 

[sharedCache removeAllCachedResponses];

}


우선 이렇게 처리했을 때 메모리 부족 현상이 줄어들었고, Instruments - Allocations 로 메모리 사용 현황을 추적해보니 어느 정도 자원의 해제가 잘 되고 있었습니다.

Posted by 삼스