Search code examples
iphoneobjective-ccachingnsdata

clear cache and memory after using NSdata to download a PDF


How would I go about cleaning the cache data and other memory while using this code? CFData (store) on simulator keeps on growing....

-(void)downloadFile:(NSURL *)theURL
{
    NSLog(@"dowbload this url : %@",theURL);

    NSURL *url = theURL;

    NSData *data = [NSData dataWithContentsOfURL:url];

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

    NSString *documentsDirectory = [paths objectAtIndex:0];

    NSString *pdfPath = [documentsDirectory stringByAppendingPathComponent:@"PDF2.pdf"];

    [data writeToFile:pdfPath atomically:YES];

    [self showThePDF];
    NSURLCache *sharedCache = [[NSURLCache alloc] initWithMemoryCapacity:0 diskCapacity:0 diskPath:nil];
    [NSURLCache setSharedURLCache:sharedCache];
    [sharedCache removeAllCachedResponses];
    [sharedCache release];
}

Solution

  • I've had a similar problem to this recently.

    Essentially dataWithContentsOfURL is using NSURLConnection under the hood, which caches the response.

    I would recommend a couple of things:

    Use NSURLConnection yourself to get the data instead of dataWithContentsOfURL.

    Use the async NSURLConnection API and delegate methods (there's rarely a need for sync methods).

    Implement the NSURLConnection delegate method below and return nil in it:

    - (NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse
    {
        return nil;
    }
    

    This ensures the responses are not cached.

    NSURLConnection documentation: http://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSURLConnection_Class/Reference/Reference.html

    Using NSURLConnection: http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/URLLoadingSystem/Tasks/UsingNSURLConnection.html