Search code examples
iosobjective-cnsdate

IOS/Objective-c: dateWithTimeInterval Issue


I don't know if this is a typo or what but for some reason, the following is not working.

I want to add a second to an NSDate. Before doing so, I check whether the date is null or nil and if so, set it to the current date to avoid errors. Despite this, after trying to add or subtract the second, the date is showing null. Can anyone suggest what is wrong?

int secondsAdjustment = 1;
NSDate* myLastViewed = item.lastviewed;
    NSDate* myLastTouched = item.lasttouched;


 if ([myLastViewed isKindOfClass:[NSNull class] ]||myLastViewed==nil) {
        NSLog(@"last viewed null");
        if ([myLastTouched isKindOfClass:[NSNull class]]||myLastTouched==nil) {
            NSLog(@"last touched is also null so set both to now");
             myLastViewed = [NSDate date];
            myLastTouched = [NSDate date];
            NSLog(@"my LastViewed after setting to now is:%@",myLastViewed);
            NSLog(@"my LastTouched after setting to now is:%@",myLastTouched);
        }
        else {
            NSLog(@"last touched is not null so I will set viewed to it");
            myLastViewed=myLastTouched;
        }
    }

if (myLastViewed!=nil&&![myLastViewed isKindOfClass:[NSNull class]]) {
         _lastViewedAdjusted = [NSDate dateWithTimeInterval:secondsAdjustment sinceDate:myLastViewed]; 
NSLog(@"making adjustment"); //THIS Logs  
    }
else {
 NSLog(@"something went wrong"); //THIS DOES NOT.  Never get here
}
NSLog(@"lastViewedAdjusted%@",_lastViewedAdjusted);//THIS IS logging as NULL

Solution

  • you can just use this

      NSDate *lastViewedAdjusted = [myLastViewed dateByAddingTimeInterval:1];