2012-11-06 93 views
1

我想查看我的字典在控制檯日誌中的對象類。至於標準NSObject子類,我在類別覆蓋-(NSString*) descriptionNSDictionary的細化描述

-(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的對象。也許還有另一種解決方案,我也會爲此感謝。

+0

你可以嘗試明確調用'description'嗎? – trojanfoe

+0

你的意思是遍歷字典嗎?迭代會很困難,因爲字典足夠複雜,其中一個孩子是不正確的。 – brigadir

+0

我認爲@trojanfoe建議用'[[self objectForKey:key] description]' – Felix

回答

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

你可能會想傳遞一個遞增縮進計數器,以便您可以格式化子對象較好,但你應該明白了。

+0

謝謝。這對定製案例有意義。我在數組中混合了字典,所以我應該調整這個方法...... – brigadir

+0

@brigadir實際上'_description:'會更好地實現爲某個實用類的類方法,因此可用於多個對象,而不僅僅是這個。 – trojanfoe