2010-08-30 64 views
6

在紅寶石中,我可以從一個物體中檢查以瞭解細節。我該如何做目標c中的類似事情?謝謝。如何檢查客觀的c對象?

+0

這是真正的問題嗎?這一個或那一個http://stackoverflow.com/questions/3597186/how-can-i-inspect-an-objective-c-object,無論是與重複垃圾郵件的方式皺起了眉頭... – t0mm13b 2010-08-30 00:42:53

+0

@ tommieb75:給出問題的相同發佈時間和內容,我會說這是一個簡單的雙重發布錯誤。 – 2010-08-30 00:50:19

+0

對不起,我認爲我的網絡不穩定,所以它提出了兩個問題。 – Tattat 2010-08-30 00:55:11

回答

5

如果你只是想要一些打印,您可以使用description像以前那樣說。

我自己並不是一個紅寶石男人,但是如果我正確理解這個,.inspect在Ruby中打印一個對象的所有實例變量。這不是Cocoa內置的東西。如果你需要這個,你可以使用運行時系統來查詢這些信息。

這裏是一個快速的I類放在一起,其確實是:

#import <objc/objc-class.h> 

@interface NSObject (InspectAsInRuby) 

- (NSString *) inspect; 

@end 

@implementation NSObject (InspectAsInRuby) 

- (NSString *) inspect; 
{ 
    NSMutableString *result = [NSMutableString stringWithFormat: @"<%@:%p", NSStringFromClass([self class]), self ]; 

    unsigned ivarCount = 0; 
    Ivar *ivarList = class_copyIvarList([self class], &ivarCount); 

    for (unsigned i = 0; i < ivarCount; i++) { 
     NSString *varName = [NSString stringWithUTF8String: ivar_getName(ivarList[i])]; 
     [result appendFormat: @" %@=%@", varName, [self valueForKey: varName]]; 
    } 

    [result appendString: @">"]; 

    free(ivarList); 

    return result; 
} 

@end 
+0

此方法不會列出任何運行時或私有iVars。 – Berik 2012-06-06 11:27:42

5

-[NSObject description]提供了一個對象的基本描述(類似於在Java中的toString-我真的不知道在Ruby中.inspect)。當您在NSLog(例如NSLog(@"@%", myObject))中打印對象時,將自動調用description

對於其他自省方法,我建議看看NSObject參考。還有很多事情可以直接使用the Objective-C runtime

2

剛打印出來與NSLog的

NSLog(@"%@", myObject); 

它會自動調用對象的方法description。如果這是您創建的課程,則需要定義該課程(返回信息爲NSString)。

看一看this question

1

在你的NSObject的.h文件這樣寫:

  • (NSDictionary的*)dictionaryRepresentation;

在你NSObject中的M檔寫:

  • (NSDictionary的*)dictionaryRepresentation { 無符號整型數= 0; //獲取班級中所有屬性的列表。 objc_property_t * properties = class_copyPropertyList([self class],& count);

    NSMutableDictionary * dictionary = [[NSMutableDictionary alloc] initWithCapacity:count];對於(int i = 0; i < count; i ++){ NSString * key = [NSString stringWithUTF8String:property_getName(properties [i])]]; NSString * value = [self valueForKey:key];

    // Only add to the NSDictionary if it's not nil. 
    if (value) 
        [dictionary setObject:value forKey:key]; 
    

    }

    免費(屬性);

    return dictionary; }

  • (NSString *)description { return [NSString stringWithFormat:@「%@」,[self dictionaryRepresentation]]; }