iOS: Detect memory constraints before allocating objects - ios

Is there a technique for avoiding undue memory consumption by testing the availability of memory before it's allocated? I understand that the general iOS approach is to optimize memory usage and respond to didReceiveMemoryWarning when necessary, but sometimes that doesn't cut it.
In my use case (image processing), I'm allocating space for a (potentially) large image using UIGraphicsBeginImageContext(). If the image is too big, I eventually get a didReceiveMemoryWarning. But, it's too late at that point: from a user experience perspective, it would've been better to prevent the user from working with such a large image to begin with; it would make more sense to say, "Sorry! Image size too big! Do something else!" before creating it than to say, "Ooops! Crashing now!"
I found a few SO threads on querying available memory and/or total physical memory, but using them is a messy and unreliable solution: there's no way to tell how much memory the OS is actually going to let you use at a given point in time, regardless of how much is free.
Basically, I want these semantics: (in "Swift-Java-ese")
try {
UIGraphicsBeginImageContext(CGRect(x: reallyBig, y: reallyBig))
}
catch NotEnoughMemoryException {
directUserToPickSmallerImage()
}
// The memory is mine; it's OK to use it
continueUsingBigImage()
Is there a methodology for doing this in iOS?

You might try pre-flitting with NSMutableData var length: Int and check for nil.
let data: NSMutableData? = NSMutableData(length:1000)
if data != nil {
println("Success")
}
else {
println("Failure")
}

Related

FileHandle don't free memory in iOS

I'll send large file to server. The file will be separated to chunks. I receive high memory consumption when I call FileHandle.readData(ofLength:). Memory for chunk don't deallocate, and after some time I receive EOM exception and crash.
Profiler show problem in FileHandle.readData(ofLength:) (see screenshots)
func nextChunk(then: #escaping (Data?) -> Void) {
self.previousOffset = self.fileHandle.offsetInFile
autoreleasepool {
let data = self.fileHandle.readData(ofLength: Constants.chunkLength)
if data == Constants.endOfFile {
then(nil)
} else {
then(data)
self.currentChunk += 1
}
}
}
The allocations tool is simply showing you where the unreleased memory was initially allocated. It is up to you to figure out what you subsequently did with that object and why it was not released in a timely manner. None of the profiling tools can help you with that. They can only point to where the object was originally allocated, which is only the starting point for your research.
One possible problem might be if you are creating Data-based URLRequest objects. That means that while the associated URLSessionTask requests are in progress, the Data is held in memory. If so, you might consider using a file-based uploadTask instead. That prevents the holding the Data associated with the body of the request in memory.
Once your start using file-based uploadTask, that begs the question as to whether you need/want to break it up into chunks at all. A file-based uploadTask, even when sending very large assets, requires very little RAM at runtime. And, at some future point in time, you may even consider using a background session, so the uploads will continue even if the user leaves the app. The combination of these features may obviate the chunking altogether.
As you may have surmised, the autoreleasepool may be unnecessary. That is intended to solve a very specific problem (where one create and release autorelease objects in a tight loop). I suspect your problem rests elsewhere.

How do I tell what objects are specifically consuming all the memory/RAM in my iOS app?

Say I have an app and I notice it has high memory usage. How do I determine WHAT is taking up all the memory in terms of specific object(s). Can I do this through the Xcode Memory Debugger somehow? Instruments?
Take this code example:
class RootViewController: UIViewController {
var image: UIImage?
override func viewDidLoad() {
super.viewDidLoad()
let data = try! Data(contentsOf: URL(string: "https://effigis.com/wp-content/uploads/2015/02/Airbus_Pleiades_50cm_8bit_RGB_Yogyakarta.jpg")!)
self.image = UIImage(data: data)
}
}
The image at that URL is about 40 MB, and in this example contributes significantly to my app's large memory footprint.
How do I determine "Oh yeah, it's this UIImage right here taking up 40 MB of memory by itself!"
Short answer:
Unfortunately, there’s no simple “for this given large memory allocation, it is associated with this particular UIImage”. You can use stack traces, either in Instruments’ “Allocations” tool or the Xcode “Debug memory graph” (with “malloc stack” feature), to identify what was allocated where, but it’s exceedingly difficult to use this to track from some large malloc for the image data and the original UIImage object. For simple objects it works fine, but it’s a little more convoluted for for images.
Long answer:
The challenge with images is that that often the memory allocated for the image data is somewhat decoupled from the UIImage object itself. The allocation of the UIImage object is easily tracked back to where you instantiated it, but not the buffer for the data backing the image. Worse, when we supply this image to some image view, the stack trace for that image buffer will drop you into rendering engine call tree, not your code, making it even harder.
That having been said, using Instruments, you can often get clues about what’s going on. For example, using the “Allocations” tool, go to the list of allocations, and see what was allocated where. If you take that list, sort it by size, and you can see a stack trace, on the right, of where it was allocated:
Now in this case, I used the image in a UIImageView, and therefore the resulting allocation is buried inside the the iOS frameworks, not directly to our code. But one can infer from the stack trace that this was the result of rendering this JPG in the UI.
So, while you can’t easily conclude “oh, that’s the specific Airbus Pleiades image,” you can at least conclude that the particular allocation was associated with some JPG.
A few unrelated observations:
I suspect you were just keeping your example simple, but obviously you would never use Data(contentsOf:) from the main thread like that. Your UI will be blocked and you risk having your app killed by the watchdog process.
You'd generally initiate the network request asynchronously:
let url = URL(string: "https://effigis.com/wp-content/uploads/2015/02/Airbus_Pleiades_50cm_8bit_RGB_Yogyakarta.jpg")!
URLSession.shared.dataTask(with: url) { data, _, _ in
guard
let data = data,
let image = UIImage(data: data)
else {
return
}
DispatchQueue.main.async {
self.image = image
}
}.resume()
This not only avoids blocking the main thread, but you theoretically could use the URLResponse and Error parameters if you wanted any special handling for given errors (e.g. customized error messages in the UI or whatever).
When downloading large assets like this, if you don’t need to show the image in the UI immediately, you might use a download task instead, which has a much lower peak memory usage than Data(contentsOf:) or a dataTask:
let url = URL(string: "https://effigis.com/wp-content/uploads/2015/02/Airbus_Pleiades_50cm_8bit_RGB_Yogyakarta.jpg")!
let filename = url.lastPathComponent
URLSession.shared.downloadTask(with: url) { location, _, _ in
guard let location = location else { return }
do {
let folder = try FileManager.default.url(for: .cachesDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
.appendingPathComponent("images")
try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
let fileURL = folder.appendingPathComponent(filename)
try FileManager.default.moveItem(at: location, to: fileURL)
} catch {
print(error)
}
}.resume()
If you do this, you won't require anything close to the 40mb during the download process. That might be critical if downloading lots of assets or if you’re not immediately showing the image in the UI. Also, if you later choose to use background URLSession, you can do this with download tasks, but not data tasks.
It’s worth noting that JPG images (and to a lesser degree, PNG images) are generally compressed. Thus, you can easily find that you might be downloading an asset whose size may be measured in kilobytes, but when you go to use it, will require megabytes. The general rule of thumb is that, regardless of the size of the file you use or the size of the control in which you’re using it, the memory required when you use the image is generally 4 × width × height (measured in pixels).
For example, a 5,494 × 5,839 px image may take up 122 mb (!) when you go to use it. The particulars may vary, but 4 × width × height is a good assumption. When considering memory consumption, the size of the file is a misleading indication of the amount of memory that might be used when you go to use this asset. Always consider the actual image dimensions because it’s going to be uncompressed when you use it.
In my answer above, I focused on Instruments’ Allocations tool. But it's worth noting that when diagnosing memory usage, the “Debug Memory Graph” feature is great when you’re trying to diagnose where the strong references are (great for identifying strong reference cycles). It’s not really relevant to this particular discussion, but can be useful if you’re tracking down where you used an image.
For example, here, I’ve downloaded your image (using URLSession) and not only set the image property of my view controller, but also used it in a UIImageView. This “Debug Memory Graph” tool is great for visualizing what is used where (but admittedly, not for correlating specific memory allocations to code):
I also editing my scheme’s diagnostic options to include the “malloc stack” feature, giving me the stack trace, on the right, like you see in the Allocations tool, above.
The Allocations instrument in Instruments can do this. Choosing Allocations List from the jump bar will show every memory allocation your app makes. Sort the table by allocation size to see the largest memory allocations.
What most developers are interested in is finding the code that allocates large amounts of memory. I answered that question at the following link:
Using instruments tool to locate leaks
I know the title of the question is about leaks, but the technique works the same for memory allocations.

Memory leak: steady increase in memory usage with simple device motion logging

Consider this simple Swift code that logs device motion data to a CSV file on disk.
let motionManager = CMMotionManager()
var handle: NSFileHandle? = nil
override func viewDidLoad() {
super.viewDidLoad()
let documents = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString
let file = documents.stringByAppendingPathComponent("/data.csv")
NSFileManager.defaultManager().createFileAtPath(file, contents: nil, attributes: nil)
handle = NSFileHandle(forUpdatingAtPath: file)
motionManager.startDeviceMotionUpdatesToQueue(NSOperationQueue.currentQueue(), withHandler: {(data, error) in
let data_points = [data.timestamp, data.attitude.roll, data.attitude.pitch, data.attitude.yaw, data.userAcceleration.x,
data.userAcceleration.y, data.userAcceleration.z, data.rotationRate.x, data.rotationRate.y, data.rotationRate.z]
let line = ",".join(data_points.map { $0.description }) + "\n"
let encoded = line.dataUsingEncoding(NSUTF8StringEncoding)!
self.handle!.writeData(encoded)
})
}
I've been stuck on this for days. There appears to be a memory leak, as memory
consumption steadily increases until the OS suspends the app for exceeding resources.
It's critical that this app be able to run for long periods without interruption. Some notes:
I've tried using NSOutputStream and a CSV-writing library (CHCSVParser), but the issue is still present
Executing the logging code asynchronously (wrapping startDeviceMotionUpdatesToQueue in dispatch_async) does not remove the issue
Performing the sensor data processing in a background NSOperationQueue does fix the issue (only when maxConcurrentOperationCount >= 2). However, that causes concurrency issues in file writing: the output file is garbled with lines intertwined between each other.
The issue does not seem to appear when logging accelerometer data only, but does seem to appear when logging multiple sensors (e.g. accelerometer + gyroscope). Perhaps there's a threshold of file writing throughput that triggers this issue?
The memory spikes seem to be spaced out at roughly 10 second intervals (steps in the above graph). Perhaps that's indicative of something? (could be an artifact of the memory instrumentation infrastructure, or perhaps it's garbage collection)
Any pointers? I've tried to use Instruments, but I don't have the skills the use it effectively. It seems that the exploding memory usage is caused by __NSOperationInternal. Here's a sample Instruments trace.
Thank you.
First, see this answer of mine:
https://stackoverflow.com/a/28566113/341994
You should not be looking at the Memory graphs in the debugger; believe only what Instruments tells you. Debug builds and Release builds are memory-managed very differently in Swift.
Second, if there is still trouble, try wrapping the interior of your handler in an autoreleasepool closure. I do not expect that that would make a difference, however (as this is not a loop), and I do not expect that it will be necessary, as I suspect that using Instruments will reveal that there was never any problem in the first place. However, the autoreleasepool call will make sure that autoreleased objects are not given a chance to accumulate.

Adobe Air 3 iOS app memory leak issue maybe related to getDefinitionByName class

I'm developing an application with adobe air 3 for ios and having low memory errors frequently.
After ios 5 update os started to kill my app after some low memory warnings.
But the thing is profiler says app uses 4 to 9 megs of memory.
There are a lot of bitmap copy operations around and sometimes instantiates new bitmaps from embedded bitmaps.
I highly optimized everything and look for leaks etc.
I watch profiler for memory status and seems like GC clears everything. everything looks perfect but app continues to get low memory errors and gets killed by os.
Is there anything wrong with this code below. Because my assumption is this ClassReference never gets off from memory even the profiles says memory is cleared.
I used clone method to pass value instead of pass by ref. so I guess GC can collect that local variable. I tried with and without clone nothing changes.
If the code below runs 10-15 times with different tile Id's app crashes but with same ID's it continues working.
Is there anyone who is familiar with this kind of thing?
tmp is bitmapData
if (isMoving)
{
tmp=getProxyImage(x,y); //low resolution tile image
}
else
{
strTmp="main_TILE"+getTileID(x,y);
var ClassReference:Class = getDefinitionByName(strTmp) as Class; //full resolution tile image //something wrong here
tmp=new ClassReference().bitmapData.clone(); //something wrong here
ClassReference=null;
}
return tmp.clone();
Thanks for reading. I hope some one has a solution for this.
You are creating three copies of your bitmapdata with this. They will likely get garbage collected eventually, but you probably run out of memory before that happens.
(Here I assume you have embedded your bitmapdata using the [Embed] tag)
tmp = new ClassReference()
// allocates no new memory, class reference already exists
var ClassReference:Class = getDefinitionByName(strTmp) as Class;
// creates a new BitmapAsset from the class reference including it's BitmapData.
// then you clone this bitmapdata, giving you two
tmp = new ClassReference().bitmapData.clone();
// not really necessary since ClassReference goes out of scope anyway, but no harm done
ClassReference=null;
// Makes a third copy of your second copy and returns it.
return tmp.clone();
I would recommend this (assuming you need unique bitmapDatas for each tile)
var ClassReference:Class = getDefinitionByName(strTmp) as Class;
return new ClassReference().bitmapData.clone();
If you don't need unique bitmapDatas, keep static properties with the bitmapDatas on some class and use the same ones all over. That will minimize memory usage.

Loading Images in J2ME?

I'm not so new to the concepts present on J2ME, but I'm sort of lazy in ways I shouldn't:
Lately my app has been loading images into memory as they were candy...
Sprite example = new Sprite(Image.createImage("/images/example.png"), w, h);
and I'm not really sure it's the best way, but it worked fine in my Motorola Z6, until last night, when I tested the app in a old Samsung cellphone and the images wont even load and require several attemps of starting the thread to show up. The screen was left on white, so I realized that it has to be something about Image loading that I'm not doing quite well... Is there anyone who can tell me how to properly make a loading routine in my app?.
I'm not sure exactly what you are looking for, but the behavior you describe very much sounds like you are experiencing an OutOfMemory exception. Try reducing the dimensions of your images (heap usage is based on dimension) and see if the behavior ceases. This will let you know if it is truly an OutOfMemory issue or something else.
Other tips:
Load images largest to smallest. This helps with heap fragmentation and allows the largest heap space for the largest images.
Unload (set to null) in reverse order of how you loaded and garbage collect after doing so. Make sure to Thread.yield() after you call the GC.
Make sure you only load the images that you need. Unload images from a state that the application is no longer in.
Since you are creating sprites you may have multiple sprites for one image. Consider creating an image pool to make sure you only load the image once. Then just point each Sprite object to the image within the pool that it requires. Your example in your question seems like you would more than likely load the same image into memory more than once. That's wasteful and could be part of the OutOfMemory issue.
Using a film image(a set of images by a defined dimension in one image) and use logic to pull them out one at a time.
Because they a grouped into one image, you are saving header space per image and thus can reduce the memory used.
This techniques was first used in MIDP 1.0 memory constrained devices.
Using the Fostah approach of not loading images over and over, I made the following class:
public class ImageLoader {
private static Hashtable pool = new Hashtable();
public static Image getSprite(String source){
if(pool.get(source) != null) return (Image) pool.get(source);
try {
Image temp = Image.createImage(source);
pool.put(source, temp);
return temp;
} catch (IOException e){
System.err.println("Error al cargar la imagen en "+source+": "+e.getMessage());
}
return null;
}
}
So, whenever I need an image I first ask the pool for it, or just load it into the pool.

Resources