是否可以在 Objective-C 泛型中反省数组的类型 -- Xcode 7+
Is it possible to introspect the array's type in Objective-C Generics -- Xcode 7+
我用它来获取 属性 名称的 class:
- (Class)gm_classForPropertyName:(NSString *)propertyName {
objc_property_t prop = class_getProperty([self class], propertyName.UTF8String);
const char * attr = property_getAttributes(prop);
NSString *attributes = [NSString stringWithUTF8String:attr];
NSArray *components = [attributes componentsSeparatedByString:@"\""];
Class propertyClass;
for (NSString *component in components) {
Class class = NSClassFromString(component);
if (class) {
propertyClass = class;
break;
} else {
class = swiftClassMapping[component];
if (class) {
propertyClass = class;
break;
}
}
}
return propertyClass;
}
但这是重要的部分:
objc_property_t prop = class_getProperty([self class], propertyName.UTF8String);
const char * attr = property_getAttributes(prop);
NSString *attributes = [NSString stringWithUTF8String:attr];
当我记录 attributes
时,它看起来仍然像一个未类型化的 NSArray 字符串。有什么方法可以反省 class 类型吗?
T@"NSArray",&,N,V_children
tl;博士
拿这个class:
@interface SomeClass : NSObject <GenomeObject>
@property (strong, nonatomic) NSArray<SomeOtherClass *> *children;
@end
鉴于 class SomeClass
和 属性 名称 children
有没有办法让我发现 children
是 SomeOtherClass
类型对象?
根据 WWDC 对这个特性的讨论,它是使用类型擦除实现的。这意味着有关泛型的信息在编译期间被删除,并且在运行时不存在。
这是相关视频:https://developer.apple.com/videos/wwdc/2015/?id=401。 lightweight generics
讨论大约在 22 分钟后开始。在 27:20 他们解释说它是使用类型擦除实现的。
我用它来获取 属性 名称的 class:
- (Class)gm_classForPropertyName:(NSString *)propertyName {
objc_property_t prop = class_getProperty([self class], propertyName.UTF8String);
const char * attr = property_getAttributes(prop);
NSString *attributes = [NSString stringWithUTF8String:attr];
NSArray *components = [attributes componentsSeparatedByString:@"\""];
Class propertyClass;
for (NSString *component in components) {
Class class = NSClassFromString(component);
if (class) {
propertyClass = class;
break;
} else {
class = swiftClassMapping[component];
if (class) {
propertyClass = class;
break;
}
}
}
return propertyClass;
}
但这是重要的部分:
objc_property_t prop = class_getProperty([self class], propertyName.UTF8String);
const char * attr = property_getAttributes(prop);
NSString *attributes = [NSString stringWithUTF8String:attr];
当我记录 attributes
时,它看起来仍然像一个未类型化的 NSArray 字符串。有什么方法可以反省 class 类型吗?
T@"NSArray",&,N,V_children
tl;博士
拿这个class:
@interface SomeClass : NSObject <GenomeObject>
@property (strong, nonatomic) NSArray<SomeOtherClass *> *children;
@end
鉴于 class SomeClass
和 属性 名称 children
有没有办法让我发现 children
是 SomeOtherClass
类型对象?
根据 WWDC 对这个特性的讨论,它是使用类型擦除实现的。这意味着有关泛型的信息在编译期间被删除,并且在运行时不存在。
这是相关视频:https://developer.apple.com/videos/wwdc/2015/?id=401。 lightweight generics
讨论大约在 22 分钟后开始。在 27:20 他们解释说它是使用类型擦除实现的。