Hello! I'm using Core ML to do some machine learning predictions.
It seems that I have to put the call to "predictionWithFeatures" in an autoreleasepool block, otherwise it will leak memory like crazy. (This is in a project with ARC turned off.)
I need to be able to use the results of the prediction outside of the function that does the predictions.
So, no problem, I just 'retain' the object that gets returned, right? Except that the autoreleasepool seems to free the object even though its retain count is 3. (Aside: why is it 3?)
If anybody can tell me why the autoreleasepool block is freeing objects that have been retained, I would greatly appreciate it. Thank you!
Pseudocode below...
myCoreMLModelOutput *outputGlobal = NULL;
void DoPredictions()
{
if (outputGlobal != NULL) {
[outputGlobal release];
outputGlobal = NULL;
}
...
@autoreleasepool { // necessary to prevent predictionFromFeatures from leaking memory
outputGlobal = [myCoreMLModel predictionFromFeatures ...];
[outputGlobal retain]; // need to be able to access this later
printf("retain count: %d\n", (int)[outputGlobal retainCount]); // why is this 3 and not 1 or 2?
}
DoSomethingWithOutputGlobal(); // crashes ... why was outputGlobal released?!
}
(Aside: why is it 3?)
The value returned by retainCount
is never easy to understand. I generally recommend that you avoid looking at it. A better way to understand this stuff is with the Allocations instrument, which shows retains, releases, and autoreleases and also has smarts to match them up.
otherwise it will leak memory like crazy.
Leak? You seem to be using terms is a non-standard way. In Apple parlance a leak is memory that can’t ever be freed. If the autorelease pool is freeing it then it wasn’t leaked, it was just building up in the autorelease pool.
Still, that doesn’t explain the crash you’re seeing. If you run with zombies, does DoSomethingWithOutputGlobal
trigger a zombie?
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"