-1

I'm using valueForKey: to check isKindOfClass:. But some of these do not have a value and thus don't return anything. How do I test the actual key rather than the value of the key? If object.animal is an NSString with @"Cat" then obviously [[object valueForKey @"animal"] isKindOfClass:[NSString class]] checks out as a string. But if object.animal hasn't been given a value, I still want to know what kind of property animal was meant to be.

Borys Verebskyi
  • 4,160
  • 6
  • 28
  • 42
Bill3
  • 61
  • 9
  • How can it be unclear what I'm asking if someone answered it? Not only answered it, but did so fairly quickly. Although closed because it's answered wouldn't be a bad reason. – Bill3 Apr 18 '16 at 02:57

2 Answers2

0

Answer to your question is here property type or class using reflection

Although I must point out using this is highly unadvisable. You might want to re think your approach if your really need to resort to this.

Community
  • 1
  • 1
stringCode
  • 2,274
  • 1
  • 23
  • 32
  • Why down vote? This is legitimate answer to his question. Even though what he is trying to do is unadvisable, but it is possible – stringCode Mar 11 '16 at 16:29
  • I didn't downvote. Although I see it all the time in questions and answers. – Bill3 Mar 11 '16 at 17:04
0

You can obtain this information using Objective-C runtime for properties. If you have

@property (readonly) NSString *animal;

You can use following code:

#import <objc/runtime.h>

// ... 

objc_property_t property = class_getProperty(object.class, "animal");
const char* attr = (property != NULL) ? property_getAttributes(property) : NULL;

attr is C string, like following: "T@\"NSString\",R". You can extract class name from this string. See Apple documentation regarding property_getAttributes result. Note that this solution will only work, if animal is declared as property.

Much easier way to handle this situation:

@interface MyObject : NSObject

@property (readonly) NSString *animal;
+ (Class)animalClass;

@end

@implementation MyObject

+ (Class)animalClass {
    return [NSString class];
}

@end
Borys Verebskyi
  • 4,160
  • 6
  • 28
  • 42