Trouble comparing TimeInterval to Integer
I'm trying to compare the timeInterval to an integer value, so I try and convert the timeInterval to an integer and compare. But I'm getting an error 'Cannot convert to a pointer type':
NSTimeInterval timeInterval = [startTime timeIntervalSinceNow];
int intSecondsElapsed = [timeInterval intValue]; // Error here !!!!
if ([counterInt != intSecondsElapsed])
{
// Do something here...
}
How would go about doing this ?
EDIT: Include more detail relating to Execute error.
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
//[formatter setDateFormat:@"HH:开发者_Go百科mm:ss"];
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
startTime = [NSDate date];
[formatter release];
if ([deviceType isEqualToString:@"iPhone 4"]||[deviceType isEqualToString:@"iPhone Simulator"])
{
int intSecondsElapsed = (int)[startTime timeIntervalSinceNow];
if (counterInt != intSecondsElapsed)
{
counterInt = intSecondsElapsed;
}
}
NSTimeInterval is defined as double so if you want to convert it to int you can make simple type cast
NSTimeInterval timeInterval = [startTime timeIntervalSinceNow];
int intSecondsElapsed = (int)timeInterval;
or simply
int intSecondsElapsed = (int)[startTime timeIntervalSinceNow];
Edit: If you initialize and use your startTime
variable in different functions you need to retain it then. [NSDate date]
returns autoreleased object so it becomes invalid outside the scope it was created. To make things easier declare a property with retain attribute for startTime
and create it using
self.startTime = [NSDate date];
And don't forget to release it in your class dealloc method.
What Vladimir said is exactly right, I just wanted to add that the reason that you were seeing the error "Cannot convert to a pointer type" is because you tried to send the message intValue
to timeInterval
, which you can only do if what you're sending the message to is a pointer to an object that will respond to it. The compiler tried to treat timeInterval
as a pointer, but failed.
精彩评论