gpt4 book ai didi

ios - 将 XCode 输出写入文件

转载 作者:行者123 更新时间:2023-11-29 12:42:59 30 4
gpt4 key购买 nike

<分区>

我希望 XCode 输出(来自 NSLog() 或其他)自动写入应用程序文件夹中的文件。换句话说,我只想将 XCode 区域的全部内容调试到一个文本文件中。

我看到了一些代码片段,但它们中的每一个都避免显示到 XCode 中(这是 Not Acceptable )。我只想将调试文本复制到一个文件中...有没有办法做到这一点?

EDIT 1(尝试克莱门特的回答后):

我收到链接器错误: enter image description here

EDIT 2(我是如何实现 Clement 的回答的):

我创建了一个名为 LogHelper 的新类:

LogHelper.h :

#define NSLog(args...) _Log(@"DEBUG ", __FILE__,__LINE__,__PRETTY_FUNCTION__,args);
@interface MyCustomLog : NSObject
void _Log(NSString *prefix, const char *file, int lineNumber, const char *funcName, NSString *format,...);
@end

LogHelper.m :

#import "LogHelper.h"

@implementation MyCustomLog : NSObject

void append(NSString *msg){
// get path to Documents/somefile.txt
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"myCustomLog.txt"];
// create if needed
if (![[NSFileManager defaultManager] fileExistsAtPath:path]){
fprintf(stderr,"Creating file at %s",[path UTF8String]);
[[NSData data] writeToFile:path atomically:YES];
}
// append
NSFileHandle *handle = [NSFileHandle fileHandleForWritingAtPath:path];
[handle truncateFileAtOffset:[handle seekToEndOfFile]];
[handle writeData:[msg dataUsingEncoding:NSUTF8StringEncoding]];
[handle closeFile];
}

void _Log(NSString *prefix, const char *file, int lineNumber, const char *funcName, NSString *format,...) {
va_list ap;
va_start (ap, format);
format = [format stringByAppendingString:@"\n"];
NSString *msg = [[NSString alloc] initWithFormat:[NSString stringWithFormat:@"%@",format] arguments:ap];
va_end (ap);
fprintf(stderr,"%s%50s:%3d - %s",[prefix UTF8String], funcName, lineNumber, [msg UTF8String]);
append(msg);
}
@end

我在 myApplication-Prefix.pch 中添加了 #import "LogHelper.h"

编辑 3(我找到了解决方案):

  • 我设置了一个名为“runningFromXCode”(follow this link to see how to do it)的环境变量,以在应用程序从 XCode 运行时将调试文本显示在控制台中;

  • 我将这段代码写入了 application:didFinishLaunchingWithOptions: 方法 ( source ):

    if (getenv("runningFromXCode") == NULL){
    NSArray *allPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [allPaths objectAtIndex:0];
    NSString *pathForLog = [documentsDirectory stringByAppendingPathComponent:@"log.txt"];

    freopen([pathForLog cStringUsingEncoding:NSASCIIStringEncoding],"a+",stderr);
    }

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com