NSURLCache crashes with autoreleased objects, but leaks otherwise - objective-c

CSURLCache is designed to cache resources for offline browsing, as NSURLCache only stores data in-memory.
If cachedResponse is autoreleased before returning the application crashes, if not, the objects are simply leaked.
Any light that could be shed onto this would be much appreciated.
Please note stringByEncodingURLEntities is a category method on NSString.
#interface CSURLCache : NSURLCache {} #end
#implementation CSURLCache
- (NSCachedURLResponse *)cachedResponseForRequest:(NSURLRequest *)request
{
NSString *path = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:[[[request URL] absoluteString] stringByEncodingURLEntities]];
if ([[NSFileManager defaultManager] fileExistsAtPath:path])
{
NSData *data = [[NSData alloc] initWithContentsOfFile:path];
NSURLResponse *response = [[NSURLResponse alloc] initWithURL:[request URL]
MIMEType:nil
expectedContentLength:[data length]
textEncodingName:nil];
NSCachedURLResponse *cachedResponse = [[NSCachedURLResponse alloc] initWithResponse:response
data:data];
[response release];
[data release];
return cachedResponse;
}
return nil;
}
#end
UPDATE: After submitting a radar to Apple it appears that this is a known issue (Radar #7640470).

- (NSCachedURLResponse *)cachedResponseForRequest:(NSURLRequest *)request
Well, this isn't an alloc, new, or copy method…
… and CSURLCache doesn't hold on to the object anywhere, so it's not owning it.
So, you need to autorelease it.
Of course, that means the object is doomed unless something retains it. Your app crashed because it tried to use the object after the object died.
Run your app under Instruments with the Zombies template. Look at where the app crashes and what it was doing when cachedResponseForRequest: was called. The caller needs to own the object until the time when the application would crash otherwise, and then release it.

Related

Memory issue with [NSData dataWithContentsOfFile]

I am developing application which required image caching. For doing this, I am using JMImageCache library. It is work fine for caching. But It can not release memory occupied by
following line.
[NSData dataWithContentsOfFile]
Here, is function which content code for cache image from disk.
- (UIImage *) imageFromDiskForURL:(NSString *)url {
NSData *data = [NSData dataWithContentsOfFile:cachePathForURL(url) options:0 error:NULL];
UIImage *i = [[[UIImage alloc] initWithData:data] autorelease];
data = nil;
[data release];
return i;
}
I have check it with instruments and it alloc 2.34 MB each time.
data = nil;
[data release];
Why do you expect this at all to work? Why should this release the original data? You're sending the release message to nil, which is a no-op.
Furthermore, if you don't create the object using alloc or copy, then it's autoreleased. That means if you release it once more, it will be overreleased and most likely your app is going to crash. What you need is:
One. Wrap the method call in an explicit autorelease pool:
- (UIImage *)imageFromDiskForURL:(NSString *)url
{
UIImage *i;
#autoreleasepool {
NSData *data = [NSData dataWithContentsOfFile:cachePathForURL(url) options:0 error:NULL];
i = [[UIImage alloc] initWithData:data];
}
return [i autorelease];
}
Two, alloc-init or manually release the data object:
- (UIImage *)imageFromDiskForURL:(NSString *)url
{
NSData *data = [[NSData alloc] initWithContentsOfFile:cachePathForURL(url) options:0 error:NULL];
UIImage *i = [[[UIImage alloc] initWithData:data] autorelease];
[data release];
return i;
}
alter the sequence nil and release
[data release];
data = nil;
and for clearing the cache use following delegate methods
[[JMImageCache sharedCache] removeAllObjects];
[[JMImageCache sharedCache] removeImageForURL:#"http://dundermifflin.com/i/MichaelScott.png"];
read the read me file of library
https://github.com/jakemarsh/JMImageCache/blob/master/README.markdown
What you are trying to do cannot work due to the way how UIImage uses a data you pass it. The data object is retained by the image, or more precisely by a CGImageSource that the UIImage has internally. From this data it is able to decompress and create the image any time. There is an option on CGImageSource to also keep around the decompressed data, but UIImage does not use that because it optimized for small UI graphics.
One thing that you can do to alleviate memory pressure is to not load the entire NSData into memory, but to memory-map it instead. This makes creation or recreation of the image a tad slower, but the created NSData object is very small in comparison.

Passing delegate through another object with ARC

I've got 2 classes, MPRequest and MPModel.
The MPModel class has a method to lookup something from the core data store, and if not found, creates an MPRequest to retrieve it via a standard HTTP request (The method in MPModel is static and not and instance method).
What I want is to be able to get a progress of the current HTTP request. I know how to do this, but I'm getting a little stuck on how to inform the view controller. I tried creating a protocol, defining a delegate property in the MPRequest class, altering the method in MPModel to accept this delegate, and in turn passing it to the MPRequest when it is created.
This is fine, however ARC is then releasing this delegate whilst the request is running and thus doesn't do what I want. I'm trying to avoid making my delegate object a strong reference in case it throws up any reference cycles but I don't know any other way of doing this.
To start the request, from my view controller I'm running
[MPModel findAllWithBlock:^(NSFetchedResultsController *controller, NSError *error) {
....
} sortedBy:#"name" ascending:YES delegate:self]
Inside the findAllWithBlock method, I have
MPRequest *objRequest = [MPRequest requestWithURL:url];
objRequest.delegate = delegate;
[objRequest setRequestMethod:#"GET"];
[MPUser signRequest:objRequest];
[objRequest submit:^(MPResponse *resp, NSError *err) {
...
}
And in the MPRequest class I have the following property defined :
#property (nonatomic, weak) NSObject<MPRequestDelegate> *delegate;
Any ideas or suggestions?
As requested, here is some more code on how things are being called :
In the view controller :
[MPPlace findAllWithBlock:^(NSFetchedResultsController *controller, NSError *error) {
_placesController = controller;
[_listView reloadData];
[self addAnnotationsToMap];
[_loadingView stopAnimating];
if (_placesController.fetchedObjects.count > 0) {
// We've got our places, but if they're local copies
// only, new ones may have been added so just update
// our copy
MPSyncEngine *engine = [[MPSyncEngine alloc] initWithClass:[MPPlace class]];
engine.delegate = self;
[engine isReadyToSync:YES];
[[MPSyncManager sharedSyncManager] registerSyncEngine:engine];
[[MPSyncManager sharedSyncManager] sync];
}
} sortedBy:#"name" ascending:YES delegate:self];
Here, self is never going to be released for obvious reasons, so I don't see how this is the problem.
Above, MPPlace is a subclass of MPModel, but the implementation of the findAllWithBlock:sortedBy:ascending:delegate: is entirely in MPModel
The method within MPModel looks like this
NSManagedObjectContext *context = [[MPCoreDataManager sharedInstance] managedObjectContext];
[context performBlockAndWait:^{
__block NSError *error;
NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:NSStringFromClass([self class])];
[request setSortDescriptors:#[[[NSSortDescriptor alloc] initWithKey:key ascending:asc]]];
NSFetchedResultsController *controller = [[NSFetchedResultsController alloc] initWithFetchRequest:request
managedObjectContext:context
sectionNameKeyPath:nil
cacheName:nil];
[controller performFetch:&error];
if (!controller.fetchedObjects || controller.fetchedObjects.count == 0) {
// Nothing found or an error, query the server instead
NSString *url = [NSString stringWithFormat:#"%#%#", kMP_BASE_API_URL, [self baseURL]];
MPRequest *objRequest = [MPRequest requestWithURL:url];
objRequest.delegate = delegate;
[objRequest setRequestMethod:#"GET"];
[MPUser signRequest:objRequest];
[objRequest submit:^(MPResponse *resp, NSError *err) {
if (err) {
block(nil, err);
} else {
NSArray *objects = [self createListWithResponse:resp];
objects = [MPModel saveAllLocally:objects forEntityName:NSStringFromClass([self class])];
[controller performFetch:&error];
block(controller, nil);
}
}];
} else {
// Great, we found something :)
block (controller, nil);
}
}];
The delegate is simply being passed on to the MPRequest object being created. My initial concern was that the MPRequest object being created was being released by ARC (which I guess it probably is) but it didn't fix anything when I changed it. I can't make it an iVar as the method is static.
The submit method of the request looks like this :
_completionBlock = block;
_responseData = [[NSMutableData alloc] init];
[self prepareRequest];
[self prepareRequestHeaders];
_connection = [[NSURLConnection alloc] initWithRequest:_urlRequest
delegate:self];
And when the app starts downloading data, it calls :
[_responseData appendData:data];
[_delegate requestDidReceive:(float)data.length ofTotal:_contentLength];
Where _contentLength is simply a long storing the expected size of the response.
Got it working. It was partly an issue with threading, where the core data thread was ending before my request, me looking at the output from a different request entirely, and the way ARC handles memory in blocks.
Thanks for the help guys

EXC_BAD_ACCESS memory error under ARC

In the method below I'm receiving "EXC_BAD_ACCESS" on the line containing the "urlString" variable. My research suggests that this error occurs when the program sends a message to a variable that has already been released. However since I'm using ARC I'm not manually releasing memory. How can I prevent ARC from releasing this variable too soon?
-(NSMutableArray *)fetchImages:(NSInteger *)count {
//prepare URL request
NSString *urlString = [NSString stringWithFormat:#"http://foo.example.com/image?quantity=%#", count];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
//Perform request and get JSON as a NSData object
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
//Parse the retrieved JSON to an NSArray
NSError *jsonParsingError = nil;
NSArray *imageFileData = [NSJSONSerialization JSONObjectWithData:response options:0 error:&jsonParsingError];
//Create an Array to store image names
NSMutableArray *imageFileNameArray;
//Iterate through the data
for(int i=0; i<[imageFileData count];i++)
{
[imageFileNameArray addObject:[imageFileData objectAtIndex:i]];
}
return imageFileNameArray;
}
Your problem has nothing to do with ARC. NSInteger isn't a class, so you don't want to be using the %# format. %# is going to send a description method to what the system thinks is an object, but when it turns out not to be one - CRASH. To solve your problem, you have two options:
You might want:
NSString *urlString =
[NSString stringWithFormat:#"http://foo.example.com/image?quantity=%d",
*count];
Make sure the count pointer is valid first!
You might need to change your method signature to be:
-(NSMutableArray *)fetchImages:(NSInteger)count;
and then change the urlString line as follows:
NSString *urlString =
[NSString stringWithFormat:#"http://foo.example.com/image?quantity=%d",
count];
You'll also need to fix all of the callers to match the new signature.
The second option seems more "normal" to me, but without more of your program it's impossible to be more specific.
you also may want to alloc and init the
NSMutableArray *imageFileNameArray;
before adding objects to it, otherwise you'll keep crashing. So you'd have
//Create an Array to store image names
NSMutableArray *imageFileNameArray = [[NSMutableArray alloc] init];

objective-c: returning data from server

The following are methods that I am using to retrieve data from a server while displaying a UIActivityIndicator. I'm trying to put these methods in the app delegate and then call them from other classes, but I don't know how to return my JSONData. Can anybody help with this?
-(void)startProcess:(NSString *)buildURL{
UIActivityIndicatorView *aInd = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActionSheetStyleBlackTranslucent];
[aInd setFrame:CGRectMake(0, 0, 50, 50)];
[aInd startAnimating];
// then call the timeCOnsumingmethod in separate thread.
[NSThread detachNewThreadSelector:#selector(getData:) toTarget:self withObject:buildURL];
}
- (void)getData:(NSString *)buildURL{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
// Query our database for a restaurant's menus
NSURL *url = [NSURL URLWithString:buildURL];
NSError *e;
NSString *jsonreturn = [[NSString alloc] initWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&e];
NSData *jsonData = [jsonreturn dataUsingEncoding:NSUTF32BigEndianStringEncoding];
// NSError *error = nil;
[self performSelectorOnMainThread:#selector(endProcess:) withObject:jsonData waitUntilDone:YES];
[pool release];
//return jsonData;
}
- (IBAction)endProcess:(NSData *)jsonData{
// ??????????
return jsonData;
}
Not sure why got downvoted but your approach is all wrong. Here's what you want to do:
Add the UIActivityIndicatorView
Use NSURLConnection to asynchronously retrieve the data
Use NSJSONSerialization to decode the received JSON into a NSDictionary or NSArray
Remove the UIActivityIndicatorView
Your best bet would be to implement this as a separate class that takes a delegate object. You could implement a delegate protocol to indicate states like 'started network activity' (which your delegate could use to add a spinner view), and 'received data' (which would pass the decoded object back to the delegate - the delegate could then remove the spinner).
One of the benefits of this approach is you can easily set it up so that the connection/request is canceled when the object deallocs. Then you just store the request object as a property on your delegate, and when your delegate goes away, it deallocs the request, which cancels/cleans up properly.

TouchJson memory leak?

I'm using TouchJson to parse json data from facebooks graph api. I'm getting some memory leaks though, and I don't really understand why...
In my effort to find the leak, I've removed everything else, so the following code is what I'm left with. The leak is one NSCFString for each loop, and I understand that it comes from the assignement to myItem.date, but I don't understand why?
I'm using the latest version of TouchJson
NSError *error;
NSDictionary *jsonDictionary = [[CJSONDeserializer deserializer] deserializeAsDictionary:data error:&error];
NSArray *jsonArray = [jsonDictionary objectForKey:#"data"];
for (NSDictionary *jsonEntry in jsonArray) {
NSDictionary *fromDictionary = [jsonEntry objectForKey:#"from"];
NSString *userId = [fromDictionary objectForKey:#"id"];
// Continue if it is a post from Atlas
if (userId != nil && [userId isEqualToString:#"10465958627"]){
MyItem *myItem = [[MyItem alloc] init];
// This uncommented causes the leak, why?
myItem.date = [jsonEntry objectForKey:#"created_time"];
[myItem release];
}
}
Thank you for your help!
Edit: I forgot to mention that MyItem is just an object with a property like so
#property (nonatomic, copy) NSString *date;