instancetype

From The Elements Wiki
Jump to: navigation, search

This is an Oxygene Language topic about Oxygene for Cocoa
 

Oxygene Language: Intro | Structured Overview | Grammar | Keywords | Functions

Platform Support: .NET: n/a | Cocoa: fully supported | Java: n/a


The instancetype is a special type defined by the compiler for the Cocoa platform only. It maps to the matching instancetype type defined by the Objective-C language and introduced with the iOS 7 and OS X 10.9 SDKs and serves a very special purpose mostly relegated to Constructors and "init*" Methods.

Background

Traditionally, init* methods in Objective-C were defined to return the nonspecific id type, and the same has been true for most static helper methods that returned instances of the same type (such as NSString.stringWithFormat() and the like. This lead to the downside that even though those methods were returning very concrete types, the compiler could make mo assumptions about their type — hindering Code Completion, type safety and – in Oxygene's case – Type Inference.

The new instancetype type aims to fix this. It is supported as result type for class and instance methods only, and it marks the method as returning an instance of the same type as the class itself. For example, a method defined as

method MyClass.myClassWithData(...): instancetype;

would be treated as returning a MyClass instance.

instancetype is fully polymorphic, so if myClassWithData() were to be overwritten on a descendant class called MySecondClass, it would be expected to return a MySecondClass instance, instead.

As of the iOS 7 and OS X 10.9 SDKs, most of Apple's own framework classes have been updated to use instancetype instead of id for their init* and creator methods as well, giving you a much better coding experience.

When writing code in Oxygene:

  • Constructors declared with the "constructor" syntax will automatically be treated as returning instancetype.
  • init* methods will be treated as returning instancetype, regardless of whether they are declared to return instancetype (which we recommend, moving forward) or id.
  • If a method is declared as returning instancetype, the compiler will enforce "result" to be assignment compatible with only the class's type, and with the result of inherited calls that also return instanceType.

See Also