因此,如果我说得对,您想要一个给定类的实例,您可以在整个应用程序中使用它而不会丢失类的状态,但这应该只存在于您的代码的DEBUG 版本中?
好的,我们可以使用与#ifdef DEBUG 混合的单例模式来确定是否处于调试模式。
DebugManager.h
// Our Debug Class that we have just made up.
// Singleton class
@interface DebugManager : NSObject
// Some properties that we want on the class
@property (nonatomic, strong) NSString *debugName;
@property (nonatomic, readonly) NSDate *instanceCreatedOn;
// a method for us to get the shared instance of our class
+ (id)sharedDebugManager;
@end
DebugManager.m
#import "DebugManager.h"
@implementation DebugManager
// Create a shared instance of our class unless one exists already
+ (id)sharedDebugManager
{
static DebugManager *sharedDebugManager = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedDebugManager = [[self alloc] init];
});
return sharedDebugManager;
}
- (id)init
{
if (self = [super init]) {
debugName = @"Debug Instance";
instanceCreatedOn = [NSDate new];
}
return self;
}
@end
现在我们有了一个 Singleton 类设置,我们可以将以下行添加到我们的 *-Prefix.pch 中,这将为我们提供一个 DebugManager 类的实例,我们可以在整个应用程序中使用它。
#ifdef DEBUG
DebugManager *manager = [DebugManager sharedDebugManager];
#endif
请记住,当您想使用 manager 实例时,您需要将其包装在 #ifdef DEBUG 中,因为在生产环境中运行时,它不会再看到 manager 的实例。所以请确保你这样做:
#ifdef DEBUG
NSLog(@"The DebugManagers instance name is %@", [manager debugName]);
#endif
不要忘记在您的Build Settings 下的 xcode 中添加您的预处理器宏,关注this 答案以了解如何做到这一点
如果您有任何问题,请在下方提问。