2010-08-30 63 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]]; }