Search code examples
objective-cnsdatenstimeinterval

How to convert this NSTimeInterval line from Swift to Objective-C


How to convert this into Objective-C ?

let date = NSDate(timeIntervalSinceReferenceDate: interval)

I tried this:

NSDate *date = [NSDate timeIntervalSinceReferenceDate: (interval)];

It generates an error of course.

Tells me: No known class method for selector timeIntervalSinceReferenceDate:

Also here is some context:

 NSTimeInterval interval = [[NSDate alloc]init].timeIntervalSinceReferenceDate + [NSDate weekInSeconds].doubleValue;
    NSDate *date = [NSDate timeIntervalSinceReferenceDate: (interval)];
    return [self isSameWeekAsDate:(date)];

Solution

  • timeIntervalSinceReferenceDate: is not a method implemented on the NSDate class. When bridging from Objective-C to Swift, Swift does some renaming with initializers.

    In order to initialize an NSDate object in Objective-C with a reference date, you must call either the class method dateWith... or the instance method initWith...:

    NSDate * const date = [NSDate dateWithTimeIntervalSinceReferenceDate: timeInterval];
    

    or...

    NSDate * const date = [[NSDate alloc] initWithTimeIntervalSinceReferenceDate: timeInterval];
    

    I've added the const here to make this more closely match the Swift code with the let declaration.