【发布时间】:2014-03-27 22:32:33
【问题描述】:
我在运行时在objective-c中有一个NSObject,我想知道这个对象中一个属性的类,我有这个属性的名称为NSString,我该怎么做。
编辑:
IntrospectionUtility 类:
@implementation IntrospectionUtility
// this function returns an array of names of properties
+ (NSMutableArray*) getProperties:(Class)class
{
NSMutableArray *properties = [[NSMutableArray alloc] init];
unsigned int outCount, i;
objc_property_t *objc_properties = class_copyPropertyList(class, &outCount);
for(i = 0; i < outCount; i++) {
objc_property_t property = objc_properties[i];
const char *propName = property_getName(property);
if(propName) {
NSString *propertyName = [NSString stringWithCString:propName encoding:[NSString defaultCStringEncoding]];
[properties addObject:propertyName];
}
}
free(objc_properties);
return properties;
}
@end
类测试:
@interface JustAnExample : NSObject
@property (nonatomic, strong) NSString *a;
@property (nonatomic, strong) NSString *b;
@property (nonatomic, strong) NSString *c;
@property (nonatomic, strong) NSString *d;
@end
@implementation JustAnExample
- (void) justAnExampleTest
{
NSMutableArray *attributes = [IntrospectionUtility getProperties:self.class];
for (NSString *attribute in attributes) {
//i want to know the type of each attributte
}
}
@end
【问题讨论】:
-
你的意思是不调用并检查结果?
-
为什么或为什么需要它?
-
另外,您的意思是您的字符串是 NSString 上的属性名称吗?它们没有任何属性,您需要直接检查方法。
-
是的,字符串是属性的名称,可以是 nsstring 或其他类型(nsmutableArray , nsarray ....)
标签: ios objective-c introspection