我尝试使用以下代码实现线程安全文件io作为调试器:
.h文件:
#import <Foundation/Foundation.h>
@interface DebugLogsHelper : NSObject
+ (instancetype)sharedManager;
- (void)WriteLogWithString:(NSString *)message;
- (void)ApplicationStart;
@end
.m文件:
#import "DebugLogsHelper.h"
@interface DebugLogsHelper()
@property (nonatomic, strong) dispatch_queue_t concurrentLogsQueue;
@end
@implementation DebugLogsHelper
+ (instancetype)sharedManager
{
static DebugLogsHelper *sharedManager = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
[NSThread sleepForTimeInterval:2];
sharedManager = [[DebugLogsHelper alloc] init];
NSLog(@"Singleton has memory address at: %@", sharedManager);
[NSThread sleepForTimeInterval:2];
});
return sharedManager;
}
- (NSString*)CurrentSystemTime {
return [[NSDate date] description];
}
-(NSString*)getDocumentsPath
{
NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
return path;
}
- (NSString*)getLogFilePath
{
NSString *loggingFilePath = nil;
loggingFilePath = [[self getDocumentsPath] stringByAppendingPathComponent:@"/CSDebugLog.txt"];
return loggingFilePath;
}
- (void)ApplicationStart
{
[self WriteLogWithString:@"==============APP START: %@=============="];
}
- (void)WriteLogWithString:(NSString *)message
{
dispatch_barrier_async(self.concurrentLogsQueue, ^{ // 2
if(message != nil){
NSString *locationFilePath = [self getLogFilePath];
NSString *str = [NSString stringWithFormat:@"%@ %s [Line %d]: %@", [self CurrentSystemTime],__PRETTY_FUNCTION__,__LINE__,message];
FILE *fp = fopen([locationFilePath UTF8String], "a");
fprintf(fp,"%s\n", [str UTF8String]);
fclose(fp);
}
dispatch_async(dispatch_get_main_queue(), ^{ // 4
//[self postContentAddedNotification];
});
});
}
@end
我从视图控制器调用此代码时收到附加的(EXC_BAD_ACCESS
)错误:
debugInfo = [DebugLogsHelper sharedManager];
[debugInfo ApplicationStart];