Search code examples
iosobjective-cinteger-division

Objective c countOfBytesReceived over countOfBytesExpectedToReceive returns 0.000000


I am trying to work out countOfBytesReceived / countOfBytesExpectedToReceive but it either returns 0.000000 or 1.000000.

I did an NSLog on both countOfBytesReceived and countOfBytesExpectedToReceive I can see the countOfBytesExpectedToReceive remains the same as expected and countOfBytesReceived changes.

CGFloat progressRatio = [task countOfBytesReceived] / [task countOfBytesExpectedToReceive];

[progressView setProgress:progressRatio];

NSLog(@"%lld", [task countOfBytesReceived]);
NSLog(@"%lld", [task countOfBytesExpectedToReceive]);
NSLog(@"%f)", progressRatio);

but progressRatio always returns 0.000000 or 1.000000 when it shouldn't.

I have this code in a scheduledTimerWithTimeInterval so its does run every 0.01.

What am I doing wrong?


Solution

  • That is because progressRatio is calculated dividing two integer values. In C when you divide two integers you get an integer. That is. Add a casting to get a float:

    CGFloat progressRatio = (CGFloat) [task countOfBytesReceived] / (CGFloat )[task countOfBytesExpectedToReceive];