正如賈森寫道你應該使用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的,或者你可能最終得到無限遞歸。
謝謝你們,我忘了我需要使用NSString格式化字符串。非常感謝... – fuzzygoat 2009-09-17 21:36:09
@quinn:請不要隨意編輯我的帖子。如果我有拼寫錯誤或者其他問題,並且您迫切希望修復它,請隨時提供,但不要隨意將我的代碼片段重新格式化爲您最喜歡的樣式。它不會增加任何價值。 – 2009-09-18 20:29:10