Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I find out the Objective-C generics type?

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*>.

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.)

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?

like image 606
DrMickeyLauer Avatar asked Jun 16 '15 11:06

DrMickeyLauer


People also ask

Does Objective-C have generics?

Lightweight generics were added to Objective-C in Xcode 7, which allow specification of type information for collection classes. While generic types are erased at runtime, they provide more information to both the developer and compiler.

Is Objective-C still used by Apple?

While Objective-C is still supported by Apple and will likely not be deprecated anytime soon, there will be no updates to the language.

When did Apple stop using Objective-C?

Objective-C was the standard programming language supported by Apple for developing macOS (which descended from NeXTSTEP) and iOS applications using their respective application programming interfaces (APIs), Cocoa and Cocoa Touch, until the introduction of Swift in 2014.

What are generics Swift?

Generics in Swift allows you to write generic and reusable code, avoiding duplication. A generic type or function creates constraints for the current scope, requiring input values to conform to these requirements.


2 Answers

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.

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

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.

like image 66
Guillaume Algis Avatar answered Oct 10 '22 06:10

Guillaume Algis


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.

like image 43
Tiago Almeida Avatar answered Oct 10 '22 07:10

Tiago Almeida