1

我想在控制台日志中查看我的字典的对象类。至于标准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. 也许还有另一种解决方案,我也会很感激。

4

1 回答 1

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];
}

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

于 2012-11-06T13:42:54.633 回答