Ios 如何在Objective-C中将a字符串发送给AppDelegate?

Ios 如何在Objective-C中将a字符串发送给AppDelegate?,ios,objective-c,appdelegate,Ios,Objective C,Appdelegate,我已经从NSObject创建了一个类“Datetool”来记录应用程序启动的日期。但是我需要在AppDelegate中显示startTime字符串 我尝试使用块发送带有“AppDelegate.h”中声明的变量的字符串,但是,在Datetool的方法initialize中无法获取该字符串 Datetool.m static NSString *startTime2; +(void)initialize { if (self == [DateTool self]) {

我已经从NSObject创建了一个类“Datetool”来记录应用程序启动的日期。但是我需要在AppDelegate中显示startTime字符串

我尝试使用块发送带有“AppDelegate.h”中声明的变量的字符串,但是,在Datetool的方法
initialize
中无法获取该字符串

Datetool.m

static NSString *startTime2;

+(void)initialize
{

   if (self == [DateTool self])
   { 
       NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
       [formatter setDateStyle:NSDateFormatterNoStyle];
       [formatter setTimeStyle:NSDateFormatterMediumStyle];
       startTime2 = [formatter stringFromDate:[NSDate date]];
    }
}

为什么不在应用程序启动时简单地调用AppDelegate中的函数(警告:我还没有尝试编译此函数)


您可以使用UIApplication的singleton方法从任何位置获取AppDelegate:
[UIApplication sharedApplication].delegate
只需将其转换为自定义类以访问特定方法:
(AppDelegate*)[UIApplication sharedApplication]。delegate

也就是说,我认为这不是正确的方法。Datetool是一个实用程序类,不应该依赖于对AppDelegate的引用,这使得代码紧密耦合。相反,Datetool应该能够从AppDelegate调用并返回所需的值。由于您已经在使用类方法,Datetool似乎根本不需要实例。您可以放弃存储静态值,只需返回所需内容:

+ (NSString*)startTime
{ 
   NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
   [formatter setDateStyle:NSDateFormatterNoStyle];
   [formatter setTimeStyle:NSDateFormatterMediumStyle];
   return [formatter stringFromDate:[NSDate date]];
}

现在,您正在从工具中提取一个值,而不是试图将其推送到AppDelegate上,将类定义导入AppDelegate.h并在AppDelegate中实例化对象是个坏主意吗?

我建议您在日期工具中提供一个委托协议,该协议由AppDelegate实现。例如(未测试):

DateTool.h:

/** The delegate protocol of DateTool. */

@protocol DateToolDelegate <NSObject>

/** The start date was set. */
- (void)startDateSet:(NSDate)startDate;

@end

@interface DateTool : NSObject

/** The delegate of DateTool. */
@property (weak) id<DateToolDelegate> delegate;

@end
在AppDelegate.h中,您需要添加协议:

#import "DateTool.h"
@interface AppDelegate : UIResponder <DateToolDelegate>
- (void)startDateSet:(NSDate)startDate
{
// Do something with startDate
}
并实施议定书:

#import "DateTool.h"
@interface AppDelegate : UIResponder <DateToolDelegate>
- (void)startDateSet:(NSDate)startDate
{
// Do something with startDate
}
希望有帮助


PS:为什么要初始化一个类方法?我建议实例化一个对象

您可以通过[UIApplication sharedApplication]访问appDelegate实例。Delegate为什么不在应用程序启动时调用appDelegate中的函数并填充局部变量?是的,我这样做了。然后,我无法通过[UIApplication sharedApplication].delegate.dateToolBlock在appdelegate中获取块。问题不清楚,但我认为OP可能存在编译器错误,因为它不知道什么是
dateToolBlock
。他需要导入
AppDelegate.h
并可能将
[UIApplication sharedApplication].delegate
转换为
(AppDelegate*)
。谢谢。真正的需求是在调用方法
initialize
时从另一个类获取日期。然后使用上面建议的委托协议。
- (void)startDateSet:(NSDate)startDate
{
// Do something with startDate
}