Pregunta

In NSURLSession, when my file is downloading I keep track of the progress with:

CGFloat progress = (CGFloat)totalBytesWritten / (CGFloat)totalBytesExpectedToWrite;

To update an on-screen indicator. I need to make sure once the download is complete though that the indicator disappears, as in my case I show the image being downloaded.

Is if (progress == 1.0) { ... } okay as a check? It may seem silly but I want to make sure there's no edge cases I'm failing to consider, as in the past I've been bit by weird division results with programming, maybe it will return 1.000000 or 1.0000001828111 or something, or could it even do something like 0.99999999999999999?

¿Fue útil?

Solución 2

The safe check using the result of the floating point division would be something like:

if (progress > (1.0f - FLT_EPSILON))

However, assuming the numbers of bytes are integers, you can simply check:

if (totalBytesWritten == totalBytesExpectedToWrite)

edit: If, as per comments, you cannot pass the integers on to wherever you need to do this check, you could also ensure that progress equals 1.0f in that case:

progress = (written < expected) ? ((CGFloat)written / expected) : 1.0f;

Otros consejos

Given:

CGFloat progress = (CGFloat)totalBytesWritten / (CGFloat)totalBytesExpectedToWrite;

It's completely reasonable to assume progress == 1.0 if (CGFloat)totalBytesWritten == (CGFloat)totalBytesExpectedToWrite is true. This should in turn be true if totalBytesWritten == totalBytesExpectedToWrite, assuming the compiler is standards-conforming, but that might be a bad assumption. There are ways the compiler could botch this by handling excess precision incorrectly, but I don't believe they apply on your target system. Still, the update ("edit") to Arkku's answer is a great idea: when you compute progress, simply force it to 1.0 if totalBytesWritten == totalBytesExpectedToWrite is true.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top