In ruby, I can .inspect from an object to know the details. How can I do the similar thing in objective c? Thank you.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With