Reputation: 1005
I am sending images very fast using a DispatchQueue, and while resulting images are small, to generate one first I have to generate a large Bitmap (8 Mb).
The problem is that when sending is too fast, the app crashes because of memory consumption. When I check it with instruments, I see that before crash, about 30 bitmaps are still allocated (240 Mb total!).
But why? With Swift's reference counting I would expect bitmap object to be deallocated at the exit of closure, no?
DispatchQueue(label: "Queue").async{
let bitmap = generateBitmap()
}
Upvotes: 0
Views: 480
Reputation: 1
ARC will indicate which object should be released from memory, but it doesn't remove that object itself. check your queue priority, maybe CPU doesn't find any time to take care of releasing objectts
Upvotes: 0
Reputation: 3816
wrap your utilization of the bitmap in a @autoreleasepool:
DispatchQueue(label: "Queue").async {
var generatedImage: UIImage?
@autoreleasepool {
let bitmap = generateBitmap()
generatedImage = makeSmallImage(from: bitmap)
}
//... use your generatedImage as you see fit. The bitmap is already released from memory at this point and is no longer retained.
}
Please note however that this assumes the image you create doesn't retain the bitmap used as source. You could confirm that by subclassing the bitmap class and verifying its deinit() function gets called.
Upvotes: 1