Coder1000 Coder1000 - 2 years ago 59
Swift Question

Casting same code in Objective-C to long gives another numerical result

EDIT: I heavily modified my question after it got a downvote. Please consider removing the downvote.


let nowMillis = 1000 * self.timeIntervalSince1970

nowMillis is: 1461865916801.75


double nowMillis = 1000 * [self timeIntervalSince1970];
NSLog([NSString stringWithFormat:@"%ld", (long)nowMillis]);

nowMillis is: -2147483648

is :
NSDate *now = [[NSDate alloc] init];
in both cases

EDIT: I realised just after asking the question: I was casting to (long) !

Answer Source

The problem is not that the code produces a different result, but that you are printing it differently. Your Objective-C tries to convert double to long, but the value overflows.

If you print it without the conversion, you should get the same result:

double nowMillis = 1000 * [self timeIntervalSince1970];
NSLog([NSString stringWithFormat:@"%f", nowMillis]);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download