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")
}