iOS7 - 存储按下按钮后使用的 NSDate 值

标签 ios ios7 nsdate

我需要在按下按钮时捕获 NSDate 的结果,以便稍后在应用程序中使用它。 执行此操作的最佳方法/代码是什么?

更新

很抱歉没有包含更多信息。此站点的新手,不了解协议(protocol)。

所以我了解如何响应按钮按下。然而,当我将 NSDate 的结果写入 timeStampLabel 时,我真正想做的是将 NSDate 的结果保存到一个键中?或类似的,以便我以后可以使用它。我要求数据可供不同的类访问,但是,如果应用程序完全关闭(即向上和从屏幕上滑动),则不需要数据保留。

我目前的代码是:

- (IBAction)tripButton:(id)sender {
    NSDate *date = [NSDate date];
    self.timeStampLabel.text = [NSString stringWithFormat:@"%@ ", date];
}

最佳答案

您可以在 App Delegate 中声明变量:

@interface AppDelegate : UIResponder <UIApplicationDelegate, UINavigationControllerDelegate> {

@property (strong, nonatomic) UIWindow *window;
@property (strong, nonatomic) UINavigationController *navigationController;

@property (nonatomic) NSDate* timeStamp;

@end

然后当您需要从任何类访问变量时,获取 App Delegate 的实例...

首先在该类的 .m 中的实现之后立即声明变量:

@implementation ClassViewController

AppDelegate *mainDelegate;

然后在viewDidLoad中初始化:

- (void)viewDidLoad {
    mainDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;

现在您可以从任何地方访问它。在这种情况下...

- (IBAction)tripButton:(id)sender {
    NSDate *date = [NSDate date];
    self.timeStampLabel.text = [NSString stringWithFormat:@"%@ ", date];
    mainDelegate.timeStamp = date;
}

然后在另一个类中,例如:

- (NSDate*)getTimeStamp {
    return mainDelegate.timeStamp;
}

关于iOS7 - 存储按下按钮后使用的 NSDate 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20597299/

相关文章:

ios - 使用 NSOutputStream,我看到 00 00 0a 00 而不是 0a 00 00 00

mysql - NSString 到 NSDate 没有正确的结果

ios - 如何按对象的多个属性对自定义对象列表进行排序

ios 7 在 vi​​ewDidAppear 中显示警报 View 导致 View 不出现

ios - JSQMessage 从未格式化的字符串设置日期属性

ios - UIDocument & NSFileWrapper 架构和性能

ios - 如何实现drawLayer :InContext in the implementation file of a UIView?

ios - Swift-如何从ENUM中获得原始值(value)

iOS:如何识别 Xcode 仪器的泄漏?

uitextview - 在 IOS7 中使用 UITextView 的 sizetofit 时发生奇怪的事情