objective c 错误 "No visible @interface for 'NSString' declares the selector 'timeIntervalSinceDate:'"

objective c error "No visible @interface for 'NSString' declares the selector 'timeIntervalSinceDate:'"

很抱歉发帖,但我一直在努力解决这个问题,我一直在尝试使用 timeIntervalSinceDate 但它不正常。这是 m 文件:

#import "ViewController.h"

@interface ViewController()

   @end

   @implementation ViewController //warning: Method definition for 'timeIntervalSinceDate:' not found

-(IBAction) setButtonTapped:(id)sender {

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

NSString *dateTimeString = [dateFormatter stringFromDate: dateTimePicker.date ];
NSLog( @"Set button tapped : %@", dateTimeString );

NSDate* currentDate = [NSDate date];
NSTimeInterval secs = [dateTimeString timeIntervalSinceDate:currentDate]; //error: No visible @interface for 'NSString' declares the selector 'timeIntervalSinceDate:’
NSLog(@"Seconds %f", secs);

[self scheduleLocalNotificationWithDate: dateTimePicker.date];

[self presentMessage:@"succesfully set!"];

}

 - (void)didReceiveMemoryWarning
 {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

@end

这是 h 文件:

#import <UIKit/UIKit.h>
#import <AvFoundation/AVFoundation.h>

@interface ViewController : UIViewController <AVAudioPlayerDelegate>
{
    IBOutlet UIDatePicker *dateTimePicker;
}
- (NSTimeInterval)timeIntervalSinceDate:dateTimePicker;
-(IBAction) setButtonTapped:(id)sender;

@end

还有 timeIntervalSinceDate 的方法是什么?我找不到任何关于它的信息,因为我是新手,所以想确定如何自己解决。

谢谢

您正在从 NSString 调用 timeIntervalSinceDate:,这是 NSDate 的一个方法。将 NSString 转换为 NSDate 使用 NSDateFormatter 并调用函数 timeIntervalSinceDate: 或者在您的情况下使用 dateTimePicker.date 本身。不要将其转换为 NSString

timeIntervalSinceDateNSDate class 的方法,并记录在 here

你在错误的类型上调用方法 NSString 这基本上是错误告诉你的。

您正在尝试对 NSString 对象 (dateTimeString) 执行 NSDate 方法。先将其转换为 NSDate 格式,然后在 NSDate 对象上调用 'timeIntervalSinceDate:' 方法。

参考这个 post 如何将 NSString 转换为 NSDate。

Converting NSString to NSDate (and back again)