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?

有帮助吗?

解决方案 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;

其他提示

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top