views:

68

answers:

4

In ruby, I can .inspect from an object to know the details. How can I do the similar thing in objective c? Thank you.

+3  A: 

-[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.

eman
+1  A: 

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.

Jorge Israel Peña
A: 

The description method of NSObject is similar to inspect

ennuikiller
+2  A: 

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
Sven