也许在NSArray中获取ObjectType的名称?

时间:2016-04-19 08:12:45

标签: ios objective-c properties nsarray objective-c-runtime

我有自定义课程如下:

@interface TestObject : NSObject
  @property (nonatomic, retain) NSArray<ObjA *> *obja;
  @property (nonatomic, retain) NSString *status;
  @property (nonatomic, retain) NSString *keyword;
  @property (nonatomic, retain) ObjB *objb;
@end

我想获取ObjectType的属性名称 obja ObjArea ),但它只返回NSArray。我得到了其他财产的名称,包括 objb 。我怎样才能在运行时获得它?我有函数获取列表属性,它们的类扩展(类别)NSObject像这样。

- (NSArray *)propertyList {
    Class currentClass = [self class];
    NSMutableArray *propertyList = [[NSMutableArray alloc] init];
    do {
        unsigned int outCount, i;
        objc_property_t *properties = class_copyPropertyList(currentClass, &outCount);

        for (i = 0; i < outCount; i++) {
            objc_property_t property = properties[i];

            NSString *propertyName = [NSString stringWithFormat:@"%s", property_getName(property)];
            [propertyList addObject:propertyName];
        }
        free(properties);
        currentClass = [currentClass superclass];
    } while ([currentClass superclass]);

    return propertyList;
}

和:

- (Class) classOfPropertyNamed:(NSString*)keyPath {
    Class class = 0;

    unsigned int n = 0;
    objc_property_t* properties = class_copyPropertyList(self.class, &n);
    for (unsigned int i=0; i<n; i++) {
        objc_property_t* property = properties + i;
        NSString* name = [NSString stringWithCString:property_getName(*property) encoding:NSUTF8StringEncoding];
        if (![keyPath isEqualToString:name]) continue;

        const char* attributes = property_getAttributes(*property);
        if (attributes[1] == '@') {
            NSMutableString* className = [NSMutableString new];
            for (int j=3; attributes[j] && attributes[j]!='"'; j++)
                [className appendFormat:@"%c", attributes[j]];
            class = NSClassFromString(className);
        }
        break;
    }
    free(properties);

    return class;
}

1 个答案:

答案 0 :(得分:0)

您应该在数组中设置自定义对象,然后调用

myCustomObject = [yourArray objectAtIndex:someIndex];
myCUstomObject.name // Then do what ever you want with it

或者您可以像这样创建NSArray类型的自定义对象: enter image description here 然后这样做: enter image description here 然后使用自定义数组执行您想要的操作