Here is the compare operation I would like to do:
// foobar is the name of an ivar on some class
// i.e. NSDate *foobar;
const char *ivarType = [self getTypeForInstanceVariableWithName:@"foobar"];
const char *objType = @encode(NSDate);
if (strcmp(ivarType, objType) == 0) {
//set value
}
NSLog(@"comparing %s with %s", ivarType, objType);
Helper method:
- (const char*)getTypeForInstanceVariableWithName:(NSString *)name {
return ivar_getTypeEncoding(class_getInstanceVariable([self class], [name cStringUsingEncoding:NSUTF8StringEncoding]));
}
NSLog result:
comparing @"NSDate" with {NSDate=#}
How come @encode returns a different type syntax than ivar_getTypeEncoding()? Is there a better way to accomplish this type determination? I must be missing something here…
Thanks!
When using ivar_getTypeEncoding() you have to pay attention to the first char. Let’s see an example:
If you have a primitive type the first char will be all you get, for int it will be ‘i’, for char ‘c’, for unsigned long long ‘Q’, etc…
For objects and classes you might get more, like on your example, but the first character is what you want, like @ for objects, # for classes, : for selectors.
You can read about those types here. You can also use constants when comparing, like _C_ID, _C_CLASS, etc. Have a loot at runtime.h.
C arrays seem to be more tricky, but I’m sure you can get around that.
One problem in your code is that you’re getting the type encoding for the NSDate class, not for a NSDate object. So instead of comparing to @encode(NSDate) compare to @encode(NSDate *).
To see this type of code in action have a look at Adium’s code for example.