【问题标题】:detect the class of a property with name in objective-c [duplicate]在objective-c中检测具有名称的属性的类[重复]
【发布时间】: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


【解决方案1】:

我将此属性的名称命名为 NSString

您可以使用函数class_getProperty(Class cls, const char *name) 来查找给定类的属性。然后使用property_getAttributes(objc_property_t property) 获取属性的属性,包括编码的类型字符串。阅读Objective-C 运行时编程指南Declared Properties 部分了解更多信息。

【讨论】:

    猜你喜欢
    • 2013-03-03
    • 2011-09-03
    • 1970-01-01
    • 2011-08-08
    • 2023-03-13
    • 2010-10-20
    • 2010-10-29
    • 2012-07-12
    相关资源
    最近更新 更多