2009-09-17 100 views
1

我很確定我只是在這裏忽略了這一點而感到困惑。任何人都可以告訴我如何爲對象打印一個簡單的描述,將其實例變量的值打印到控制檯。從描述方法輸出iVars?

另外:反正是有存在的信息塊(即如果有10個高德公司將是一個痛苦讓他們都回到一個接一個)

@interface CelestialBody : NSObject { 
    NSString *bodyName; 
    int bodyMass; 
} 

- (NSString *)description { 
    return (@"Name: %@ Mass: %d", bodyName, bodyMass); 
} 

歡呼-gary-

回答

9
- (NSString*)description 
{ 
    return [NSString stringWithFormat:@"Name: %@\nMass: %d\nFoo: %@", 
    bodyName, bodyMass, foo]; 
} 
+0

謝謝你們,我忘了我需要使用NSString格式化字符串。非常感謝... – fuzzygoat 2009-09-17 21:36:09

+1

@quinn:請不要隨意編輯我的帖子。如果我有拼寫錯誤或者其他問題,並且您迫切希望修復它,請隨時提供,但不要隨意將我的代碼片段重新格式化爲您最喜歡的樣式。它不會增加任何價值。 – 2009-09-18 20:29:10

5

看答案this question。代碼複製如下:

unsigned int varCount; 

Ivar *vars = class_copyIvarList([MyClass class], &varCount); 

for (int i = 0; i < varCount; i++) { 
    Ivar var = vars[i]; 

    const char* name = ivar_getName(var); 
    const char* typeEncoding = ivar_getTypeEncoding(var); 

    // do what you wish with the name and type here 
} 

free(vars); 
+0

這在一般意義上很有用,但Jason的回答解決了提問者正確使用格式字符串時遇到的問題。 – 2009-09-17 20:08:53

+0

如果您有伊娃的名稱,然後使用'valueForKey:'讓伊娃的價值通過KVC刪除負擔檢查型的你,一切都是那麼的對象。 – PeyloW 2009-09-17 21:08:25

1

正如賈森寫道你應該使用stringWithFormat:格式化與printf語法的字符串。

-(NSString*)description; 
{ 
    return [NSString stringWithFormat:@"Name: %@ Mass: %d", bodyName, bodyMass]; 
} 

爲了避免許多類再次寫這一遍又一遍,你可以添加對NSObject的一個類別,讓您可以輕鬆地檢查實例變量。這將是一個糟糕的表現,但適用於調試目的。

@implementation NSObject (IvarDictionary) 

-(NSDictionary*)dictionaryWithIvars; 
{ 
    NSMutableDictionary* dict = [NSMutableDictionary dictionary]; 
    unsigned int ivarCount; 
    Ivar* ivars = class_copyIvarList([self class], &ivarCount); 
    for (int i = 0; i < ivarCount; i++) { 
    NSString* name = [NSString stringWithCString:ivar_getName(ivars[i]) 
             encoding:NSASCIIStringEncoding]; 
    id value = [self valueForKey:name]; 
    if (value == nil) { 
     value = [NSNull null]; 
    } 
    [dict setObject:value forKey:name]; 
    } 
    free(vars); 
    return [[dict copy] autorelease]; 
} 
@end 

有了這個實施描述地方也是小菜一碟:

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

不要加入這個description作爲一個類別上NSObject的,或者你可能最終得到無限遞歸。

1

這不是一個壞主意,你有什麼就有什麼,這幾乎達到了。

// choose a short name for the macro 
#define _f(x,...) [NSString stringWithFormat:x,__VA_ARGS__] 

... 

- (NSString *) description 
{ 
    return _f(@"Name: %@ Mass: %d", bodyName, bodyMass); 
} 
+0

謝謝,我總是在想,我怎麼能縮短認爲過於冗長stringWithFormat成語,但我不知道該怎麼辦變參於宏。現在我做的:) – 2010-10-08 09:11:14

+0

作爲一個側面說明,你可以考慮使用'## __ VA_ARGS__'的宏中更通用的可變參數的參數處理;否則你可能會得到一個編譯器錯誤,例如'return _f(@「Name is foo」);',在調用中你沒有提供可變參數列表。 – fullofsquirrels 2016-04-13 20:23:38

+0

@fullofsquirrels:但是當你應該使用'@「str」'時,爲什麼要使用'_f(@「str」)? – dreamlax 2016-04-13 23:46:54