NSDictionary的精炼描述

时间:2012-11-06 11:28:16

标签: objective-c logging nsdictionary

我想在控制台日志中看到我的字典的对象类。对于标准NSObject子类,我在类别中重写-(NSString*) description

-(NSString*) description
{
    NSMutableString* desc = [NSMutableString stringWithFormat: @"<%@ 0x%08x>\nobjects count: %ld", [self class], (uint)self, [self count]];
    for (id key in [self allKeys])
        [desc appendFormat: @"\n%@ = %@ (%@)", key, [self objectForKey: key], [[self objectForKey: key] class]];
    return desc;
}

它可以工作,但仅适用于顶级NSDictionary对象(如果对象在子级中有字典,则会绕过description方法进行记录)。因此,NSDictionary以某种方式打印其子对象,而无需在其上调用description ...

是否有办法通过我的description方法记录这些儿童词典?

PS:在实际情况中,我想在字典中找到一个无法保存到plist的对象。也许有另一种解决方案,我也会感激。

1 个答案:

答案 0 :(得分:0)

您可以编写递归description方法:

// Private Methods
@interface MyClass ()
- (NSString *)_description:(id)object;
@end

...

- (NSString *)_description:(id)object
{
    if ([object isKindOfClass:[NSDictionary class]])
    {
        NSDictionary *dict = (NSDictionary *)object;
        NSMutableString *desc = [NSMutableString stringWithFormat: @"<%@ %p>\nobjects count: %ld", [dict class], dict, [dict count]];
        for (id key in [dict allKeys])
        {
            [desc appendFormat: @"\n%@ = %@ (%@)", key, [self _description:[objectForKey: key]], [[self objectForKey: key] class]];
            return desc;
        }
    }
    else
    {
        return [(NSObject *)object description];
    }
}

- (NSString *)description
{
    return [self _description:self];
}

您可能希望传递一个递增缩进计数器,以便您可以更好地格式化子对象,但是您应该明白这一点。