开发者

How can I inspect an objective c object?

In ruby, I can .inspect from an object to know the details. How can I do the sim开发者_开发知识库ilar thing in objective c? Thank you.


If you just want something to print you can use description as said before.

I'm not a Ruby guy myself, but if I understand this correctly .inspect in Ruby prints all the instance variables of an object. This is not something built into Cocoa. If you need this you can use the runtime system to query this information.

Here is a quick category I put together which does that:

#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


-[NSObject description] provides a basic description of an object (similar to toString in Java--I don't really know about .inspect in Ruby). description is automatically called in when you print an object in NSLog (e.g. NSLog(@"@%", myObject)).

For other introspection methods, I'd suggest looking at the NSObject reference. There are also a lot of things you can do directly with the Objective-C runtime.


Just print it out with NSLog

NSLog(@"%@", myObject);

It will automatically call the object's description method. If this is a class you created, you will want to define that (return an NSString with the info).

Take a look at this question.


The description method of NSObject is similar to inspect


In your NSObject's h file write this :

  • (NSDictionary *)dictionaryRepresentation;

In your NSObject's m file write this :

  • (NSDictionary *)dictionaryRepresentation { unsigned int count = 0; // Get a list of all properties in the class. objc_property_t *properties = class_copyPropertyList([self class], &count);

    NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] initWithCapacity:count];

    for (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];
    

    }

    free(properties);

    return dictionary; }

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜