My app loads a large number of images from the server and displays them. I am using an operation queue to do the loading and a synchronous request within the operation to get the image (because asynchronous is not allowed apparently within an operation).
I am running into a cache problem. None of URL responses are getting cached and I do not know how to fix it. here is the code from my operation:
.h
Code:
@interface DRGetImageOperation : NSOperation {
NSURL *objectURL;
NSNumber *index;
UIViewController *mainViewController;
SEL callback;
}
@property (nonatomic, retain) NSURL *objectURL;
- (id)initWithViewController:(UIViewController *)viewController andIndex:(int)number;
- (void) setCallback:(SEL)select;
@end
.m
Code:
// Partial code. Some small methods are not shown
- (void)main {
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
NSLog(@"URL = %@", objectURL);
NSLog(@"Cache size before = %d bytes", [[NSURLCache sharedURLCache] currentMemoryUsage]);
NSData *data = nil;
NSHTTPURLResponse *response = NULL;
NSError *error = nil;
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:objectURL cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:20];
data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(@"Image Request finished. Error = %@",[error localizedDescription]);
NSLog(@"Cache size after = %d bytes", [[NSURLCache sharedURLCache] currentMemoryUsage]);
// Cache size = 0 ALWAYS!
if (error == nil) {
UIImage *photo = [UIImage imageWithData:data];
if (photo) {
[mainViewController performSelectorOnMainThread:callback
withObject:[NSArray arrayWithObjects:photo, index, nil]
waitUntilDone:YES];
[pool release];
return;
}
}
// ELSE (Error happened)
[mainViewController performSelectorOnMainThread:callback
withObject:[NSArray arrayWithObjects:nil]
waitUntilDone:YES];
[pool release];
}