我怎样才能找到Objective-C泛型类型?

时间:2021-04-10 19:20:33

Xcode 7 contains an Objective-C variant, where you can define a type-hint for (homogenous) NSArray return values and properties, defined such as NSArray<UIImage*>.

Xcode 7包含一个Objective-C变体,您可以在其中定义(同源)NSArray返回值和属性的类型提示,定义为NSArray

I'd like to use this feature to rewrite my JSON-deserializer class (which needs such kind of type hints – previously I have solved this by adding a -(Class)jsonHintForKey:(NSString*)key to my classes that have homogenous arrays as properties.)

我想使用这个功能来重写我的JSON-deserializer类(需要这种类型的提示 - 之前我通过在我的具有同类数组的类中添加 - (类)jsonHintForKey:(NSString *)键来解决这个问题作为属性。)

Do you know whether (and if so, how) I can use the Objective-C runtime to get the class of this new type hint at runtime?

你知道我是否可以使用Objective-C运行时在运行时获取这个新类型提示的类吗?

2 个解决方案

#1


29  

The lightweight generics introduced in Xcode 7 are just compile time hints to help the compiler raise warnings, but at run time you get the same old behavior with your variable being just NSArrays of ids.

Xcode 7中引入的轻量级泛型只是编译时提示,可以帮助编译器发出警告,但是在运行时,你的变量只是NSArrays的ids,你会得到相同的旧行为。

Source: WWDC '15 "Swift and Objective-C Interoperability" session

资料来源:WWDC '15“Swift和Objective-C互操作性”会议

See the transcript of the talk:

看到谈话的记录:

So the entire lightweight generics feature is based on a type erasure model. Which means that the compiler has all of this rich static type information but it erases that information when generating code.

因此,整个轻量级泛型功能基于类型擦除模型。这意味着编译器具有所有这些丰富的静态类型信息,但它在生成代码时会删除该信息。

#2


7  

It is not possible to do that.

这样做是不可能的。

Generics were introduced in objective-c to improve the bridge between swift and objective-c. The advantage it gives to objective-c is only useful at compile time, and I that information is lost at runtime.

在Objective-c中引入了泛型,以改善swift和objective-c之间的桥梁。它给objective-c的优势仅在编译时有用,而且我在运行时丢失了信息。

#1


29  

The lightweight generics introduced in Xcode 7 are just compile time hints to help the compiler raise warnings, but at run time you get the same old behavior with your variable being just NSArrays of ids.

Xcode 7中引入的轻量级泛型只是编译时提示,可以帮助编译器发出警告,但是在运行时,你的变量只是NSArrays的ids,你会得到相同的旧行为。

Source: WWDC '15 "Swift and Objective-C Interoperability" session

资料来源:WWDC '15“Swift和Objective-C互操作性”会议

See the transcript of the talk:

看到谈话的记录:

So the entire lightweight generics feature is based on a type erasure model. Which means that the compiler has all of this rich static type information but it erases that information when generating code.

因此,整个轻量级泛型功能基于类型擦除模型。这意味着编译器具有所有这些丰富的静态类型信息,但它在生成代码时会删除该信息。

#2


7  

It is not possible to do that.

这样做是不可能的。

Generics were introduced in objective-c to improve the bridge between swift and objective-c. The advantage it gives to objective-c is only useful at compile time, and I that information is lost at runtime.

在Objective-c中引入了泛型,以改善swift和objective-c之间的桥梁。它给objective-c的优势仅在编译时有用,而且我在运行时丢失了信息。