Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 similar thing in objective c? Thank you.

like image 852
Tattat Avatar asked Aug 30 '10 00:08

Tattat


People also ask

Is kind of class Objective-C?

Objective-C Classes Are also Objects In Objective-C, a class is itself an object with an opaque type called Class . Classes can't have properties defined using the declaration syntax shown earlier for instances, but they can receive messages.

What is ID type in Objective-C?

id is the generic object pointer, an Objective-C type representing "any object". An instance of any Objective-C class can be stored in an id variable.

What is Self Objective-C?

self is a special variable in Objective-C, inside an instance method this variable refers to the receiver(object) of the message that invoked the method, while in a class method self will indicate which class is calling.


1 Answers

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
like image 200
Sven Avatar answered Sep 20 '22 00:09

Sven