开发者

Printing a struct using description

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 {开发者_StackOverflowfloat a,b,c;}list;
    list testlist = {1.0,2.5,3.9};
    NSLog(@"%@",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.


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));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜