gpt4 book ai didi

objective-c - 在 Objective-C 和 Cocoa 中,是否有一个函数 debug_print(foobar) 可以打印出变量的名称并转储它的值?

转载 作者:行者123 更新时间:2023-12-03 17:42:10 25 4
gpt4 key购买 nike

例如:

debug_print(foobar);     // prints out:  foobar is (hello, world)
debug_print(i * 27); // prints out: i * 27 is 54

换句话说,首先按字面打印出变量或表达式,然后转储其值。

它不需要采用这种形式。它也可以作为字符串调用:

debug_print("foobar");     // prints out:  foobar is (hello, world)
debug_print("i * 27"); // prints out: i * 27 is 54

更新:或者如果不是内置的怎么写?

最佳答案

您可以使用宏

#define debug_print(expr...) NSLog(@"%@ is %@", @#expr, (expr))

如您所见,NSLog 格式字符串需要一个 %@(对象),因此您需要使用整数的变体:

#define debug_printI(expr...) NSLog(@"%@ is %d", @#expr, (expr))

编辑:

有一种方法可以使用单个宏并使其适用于所有类型:使用 @encoding 来查找类型。

NSString *print_debug_format_for_type(const char *encoding) {
switch (encoding[0]) {
case '@': return @"%@ is %@";
case '*': return @"%@ is %s";

case 'f': return @"%@ is %f";
case 'd': return @"%@ is %f";

case 'q': return @"%@ is %qi";
case 'Q': return @"%@ is %qu";

case 'c':
case 'i':
case 's':
default: return @"%@ is %d";
}
}

#define debug_print(expr...) ({ \
typedef __typeof__(expr) t; \
NSLog(print_debug_format_for_type(@encode(t)), @#expr, (expr)); \
})

有了这个,您可以在任何地方使用(几乎)任何类型的 debug_print,只要它位于 print_debug_format_for_type 中。传入的编码(来自@encode)可以在here中找到。 [apple docs],格式字符串的格式可以在here中找到。 [还有苹果文档]。按原样,这适用于任何对象、c 样式字符串、整数、浮点或 double 表达式。

(小警告:ObjC BOOL 类型实际上是一个 typedef'd 字符,因此如果您 p​​rint_debug 一个 bool 表达式,它会说它是 1 或 0。虽然这有效,但这也意味着如果您 p​​rint_debug 一个 char 表达式,它会说它是字符的 ascii 编号。要更改此行为(并中断 BOOL 打印),请将大小写“c”更改为 return @"%@ is %c"

关于objective-c - 在 Objective-C 和 Cocoa 中,是否有一个函数 debug_print(foobar) 可以打印出变量的名称并转储它的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10165325/

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