使用描述打印结构

发布于 2024-12-06 20:46:57 字数 229 浏览 1 评论 0原文

我想知道是否可以使用Cocoa框架中的description函数来记录struct的内容。例如:

    typedef struct {float a,b,c;}list;
    list testlist = {1.0,2.5,3.9};
    NSLog(@"%@",testlist); //--> 1.0,2.5,3.9

I would like to know if it is possible to use the description function in the Cocoa framework to log the contents of a struct. For example:

    typedef struct {float a,b,c;}list;
    list testlist = {1.0,2.5,3.9};
    NSLog(@"%@",testlist); //--> 1.0,2.5,3.9

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

墨落成白 2024-12-13 20:46:57

不可以。description消息是NSObject协议中的一个方法,因此根据定义,它必须是一个对象。不过,还有一种更方便的日志调试方法,即使用 LOG_EXPR() 宏。这将采用对象和结构:

LOG_EXPR(testlist);

它将输出:

测试列表={1.0,2.5,3.9};

可以找到此代码 这里

No. The description message is a method found in the NSObject protocol, so by definition, must be an object. There is, however, a more convenient way of log debugging, using a LOG_EXPR() macro. This will take objects and structs:

LOG_EXPR(testlist);

Which would output:

testlist = {1.0, 2.5, 3.9};

This code can be found here.

紫罗兰の梦幻 2024-12-13 20:46:57

description 是一种方法,因此只能在对象上调用。反过来,%@ 格式说明符仅适用于响应description 的对象。

您可以编写自己的函数,用结构的内容创建一个漂亮的 NSString

NSString * pretty_string_from_list( list l ){

    return [NSString stringWithFormat:@"<list: [%f, %f, %f]>", l.a, l.b, l.c];
}

然后在记录该结构时调用该函数:

NSLog(@"%@", pretty_string_from_list(testlist));

description is a method and as such can only be called on an object. In turn, the %@ format specifier only works for objects which respond to description.

You can write your own function to make a pretty NSString with the contents of your struct:

NSString * pretty_string_from_list( list l ){

    return [NSString stringWithFormat:@"<list: [%f, %f, %f]>", l.a, l.b, l.c];
}

Then call that function when you log the struct:

NSLog(@"%@", pretty_string_from_list(testlist));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文