I try to load a plist file from my server. I can think of 2 ways to do that, but for both Instruments says there's huge memory leak :
NSData* plistData = [NSData dataWithContentsOfURL:url];
and
NSDictionary* updateDigest = [NSDictionary dictionaryWithContentsOfURL: [NSURL URLWithString:updateURL] ];
The backtrace of the memory leak leads to __CFURLCache in CFNetwork and I am wondering if something can be done to fix the leak? Any other way to load a remote plist xml, without the memory leakage ?
Thanks
The leak probably isn't coming from loading the data. It's probably from retaining the data elsewhere and not releasing it.
Related
I have a problem with Core Data and NSMutableArray.
Reading this document: https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CoreData/Articles/cdPerformance.html#//apple_ref/doc/uid/TP40003468-SW2
in the chapter "Faulting Behavior" I read: Since isEqual and hash do not cause a fault to fire, managed objects can typically be placed in collections without firing a fault.
Ok, for this reason, I understand that I can:
- fetch the managedObjectContext
- put all managed object into an array (the objects contains image data)
without firing a fault and waste memory (until the object is accessed for the first time), correct?
But, for some reason, Core Data is firing a fault when I try to put the result in an NSMutableArray
NSArray *fetchResults = [self.managedObjectContext executeFetchRequest:request error:&error]; //this line does'n fire a fault
self.cache = [NSMutableArray arrayWithArray:fetchResults]; //this line fires a fault
self.cache is simply a NSMutableArray.
After the last line of code, I see the memory usage growing through instruments (I have 50MB of images in the DB, and the memory goes immediately from 2-3Mb to 52-53MB.
Any suggestion?
Thanks
Ok, It was my mistake looking only to the Instruments memory occupation to determine if the fault was firing.
Core Data documentation says: If you need to determine whether an object is a fault, you can send it an isFault message without firing the fault. If isFault returns NO, then the data must be in memory. However, if isFault returns YES, it does not imply that the data is not in memory. The data may be in memory, or it may not, depending on many factors influencing caching.
I added this code after the "incriminate" lines:
for (ImageCache *cache in self.cache) {
NSLog(#"Is fault? %i", [cache isFault]);
}
The result was 1 for all the objects.
Then I modified the for loop:
for (ImageCache *cache in self.cache) {
NSLog(#"Is fault? %i", [cache isFault]);
UIImageView *imageView = [[UIImageView alloc]initWithImage:cache.image];
NSLog(#"Is fault? %i", [cache isFault]);
}
The result was 1 for the first NSLog, and 0 for the second NSLog of each object (the fault fired after the access to the image)
As the documentations says, it seems that Core Data is correctly faulting my objects, the memory occupation is due to Core Data caches.
Mea culpa :-)
(although I'm still curious to see how it behaves in real low memory situations. I expect this cache to flush...trying to send a memory warning has no effects on the memory size)
Thanks
we build an iPad app that downloads a bunch of data and PDF documents from a web service (data first, documents later in the background). To do so, we use SOAP via HTTP(S) requests. It works fine and altogether, the app is running well. Problem is, if there are too many documents to download at some point the app crashes. Using Instruments I figured out that it is a memory issue, particularly NSRegularExpression and NSRunLoop. (I'm using ARC)
I could improve my code to optimize the NSRegularExpression creation. But I don't know how to improve the NSRunLoop issue.
I tried both, asynchronous and synchronous HTTP request. Using async, I had to wait for the download to finish and since sleep()/[NSThread sleepForTimeInterval:] aren't an option, I use
while ( _waitToFinish ) {
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
}
Using sync request, Instruments reveals that
[NSURLConnection sendSynchronousRequest:theRequest returningResponse:&urlResponse error:&error];
also "waits" with help of NSRunLoop and also messes up the memory.
Is this a bug in CoreFoundation or ARC?
Is there another way to idle while waiting for the requests to finish?
Thanks in advance.
Edit:
With "memory issue" I meant that the app crashes (or is killed by iOS) because it uses too much memory.
This is what Instruments shows:
The percentage get higher the longer the app is downloading.
Edit:
Going further down revealed that it is NSURLConnection, that is messing up the memory. It seems that I have somehow missed setting connection and receivedData to nil (see URL Loading System Programming Guide). This improved my memory usage again a little.
Now, there are two more big memory allocation operations:
And this is the code I think belongs to what Instruments displays:
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[_receivedData appendData:data];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *responseText = [[NSString alloc] initWithBytes:[_receivedData mutableBytes] length:[_receivedData length] encoding:NSUTF8StringEncoding];
self.lastResponse = responseText;
responseText = nil;
connection = nil;
_receivedData = nil;
_lastResult = TRUE;
_waitToFinish = FALSE;
}
Is there anything I could change to improve the code?
Edit: (Changed title from "NSRunLoop messes up iPad memory")
Edit:
I created a test app to prove that it is the NSURLConnection, that messes up the memory. Then I contacted the Apple Developer Support.
Since I am downloading a lot of PDF in an iteration with NSURLConnection, the solution was to add an #autoreleasepool { .. } in the iteration and another one around the NSRunLoop.
Thanks.
It's not a bug in Core Foundation or ARC. It's a bug in your code.
Don't run the run loop yourself. Just use +[NSURLConnection sendAsynchronousRequest:queue:completionHandler:]. It will call your completionHandler block when the request is complete. That's when you process the response. Meanwhile, just return out of your method and let the system worry about running the run loop.
You say “it's a memory issue” with NSRegularExpression and NSRunLoop, but you don't say what the issue is, or what evidence Instruments is showing you. If you describe the “issue” in more detail, maybe we can help you with that.
running my app through Instruments "Leaks" it's saying I've got a leak which seems to happen with this code -
-(void)podAppears {
podCount ++;
NSString *podName = [NSString stringWithFormat:#"Pod%i",podCount];
Pod *thePod = [[Pod alloc] initWithOwner:self withName:podName];
[pods setObject:thePod forKey:podName];
[thePod release];
}
I can't see anything wrong, but I'm fairly new to Objective-C & memory management in general. Any help much appreciated!
That code looks fine. When Instruments informs you of a leak, it tells you where the leaked object originated. It's likely that the actual leaking of that object is occurring elsewhere in your app. You should look at other locations where you access your Pod objects.
Ever since switching to XCode 4 the leaks tool shows a LOT of leakage, all from JSONKit and ASIHTTPRequest, after a 2 min run I am leaking hundreds of arrays/dictionaries/strings (from jk_create_dictionary, jk_parse_array, HTTPMessage::*, etc.) totaling a few 100s KB. Most of the stack traces don't originate in any of my calls, and the rest are completely innocent.
I am pretty positive it was not the case pre-XCode 4.
I don't know who the culprit is. Any insight would be lovely.
Update:
The JSONKit leaks are probably JSONDecoder caching.
For example:
static JSONDecoder *decoder = nil;
if (!decoder)
decoder=[[JSONDecoder alloc] init];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:url]];
[request setCachePolicy:ASIDoNotWriteToCacheCachePolicy];
[request setCompletionBlock:^{
NSData *response = [request responseData];
NSDictionary *json = [decoder objectWithUTF8String:[response bytes] length:[response length]];
// ...
}];
[request setFailedBlock:^{
// ...
}];
[request startAsynchronous];
EDIT : Before you read the rest of this answer:
If you see that kind of memory leaks, don't blame Instruments or JSONKit... Both are reliable!
...Blame yourself, 99.9% chances your code is leaking the data you parsed with JSONKit!
END_OF_EDIT
Not an answer, more a complement, and an attempt to understand what's going on since I'm seeing leaks too with instruments.
I'm using JSONKit that way :
NSArray *lines = [dataString componentsSeparatedByString:#"\n"];
for (NSString *line in lines) { // I know, strange format isn't? :)
NSDictionary *json = [line objectFromJSONStringWithParseOptions:JKParseOptionLooseUnicode];
// use dictionary data...
}
#ssteinberg, is that the kind of leaks you're having? :
Note that I had this after some heavy load testing, 500 requests with huge JSON responses, which explains leaks are in MB (using latest gh version)
Please note that I'm quite new using Instruments, and I'm not sure how to understand these results. According to Frames reported, yes that looks like Caching... but I'd like to be sure...
So I opened an Issue on GH, I hope that #johnezang, or anyone, will enlight us about this.
All my apologies if that's just a misunderstanding with Instruments, which I would prefer :)
According to Apple's WWDC 2010 videos (Advanced Memory Analysis with Instruments), false positive leaks are rare. Sometimes the Leaks tool misses leaks, but it's reliable for the ones it reports. I'm not all that great with statics, but have you checked to make sure you're not alloc'ing the decoder without releasing it? If it's not released and falls out of scope, that would constitute a leak, right?
I have the following code in a loop iterating over the different document objects:
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
NSData* data = [document primitiveValueForKey:#"data"];
[document.managedObjectContext refreshObject:document mergeChanges:NO];
[pool release];
The "data" property is a large blob (a 1MB image).
And as I monitor the memory with the Allocation Instrument memory usage is increasing. I cannot find where the leak is coming from and how to remove it.
Thanks!
Something is wrong with your sample code, did you mean:
NSData *data = [document primitiveValueForKey:#"data"];
As data is currently not assigned within the scope of your autoreleasepool it is also not released with with your autoreleasepool
Why are you using primitiveValueForKey and not a dynamic accessor?
The dynamic accessors are much more
efficient, and allow for compile-time
checking.
How about calling [pool drain] instead of [pool release]?
I managed to solve the problem by doing : [document.managedObjectContext processPendingChanges] right before draining the pool. However, I don't understand what pending changes would be there? Could someone enlighten me on that?
Your observation that processPendingChanges seems to solve the problem suggests to me that, as you import, the UndoManager for your NSManagedObjectContext is keeping track of all the changes you make as you do your bulk import.
What processPendingChanges is doing (as I understand it) is pushing changes stored in the managedObjectContext to the persistent store.
Try [[document managedObjectContext] setUndoManager:nil] (or create a new managedObjectContext for the import and set its undoManager to nil, if your document.managedObjectContext is the 'main' managedObjectContext and you don't want to turn off undo registration.