Instancetype and ID differences in OBJECTIVE-C

Source: Internet
Author: User
Tags vars


There is one of the same two different. Same written by Mattt Thompson on Dec 10th, 2012





Objective-c is a rapidly evolving language, in a-a-to-a-you-just-t see in established programming languages. ARC, Object literals, subscripting, blocks:in the span of just three years, so much of been changed (for the better).



All of the innovation is a result of Apple's philosophy of vertical integration. Just as Apple ' s investment in designing it own chipsets gave them leverage to compete aggressively with their mobile hard Ware, so too have their investment in LLVM allowed their software to keep pace.



Clang developments range from the mundane to paradigm-changing, but telling the difference takes practice. Because we ' re talking about low-level language features, it's difficult to understand what implications they Er up with API design.



One such exampleinstancetypeis, the subject of this week ' s article.



In objective-c, conventions aren ' t just a matter of coding best-practices, they is implicit instructions to the compiler.



For example,allocandinitboth has return types ofid, yet in Xcode, the compiler makes all of the correct type Che Cks. How are this possible?



In Cocoa, there is a convention so methods with names likealloc, or always return objects that was aninitinstance of The receiver class. These methods is said to has a related result type.



Class constructor methods, although they similarly returnid, don ' t get the same type-checking benefit, because they do N ' t follow that naming convention.



You can try this out for yourself:


 
 
[[[NSArray alloc] init] mediaPlaybackAllowsAirPlay]; // ? "No visible @interface for `NSArray` declares the selector `mediaPlaybackAllowsAirPlay`"

[[NSArray array] mediaPlaybackAllowsAirPlay]; // (No error)


Becauseallocinitand follow the naming convention for being a related result type, the correct type check againstNSArrayis performed. However, the equivalent class constructorarraydoes not follow that convention, and is interpreted asid.



idis useful for opting-out of type safety, but losing it when you do want it sucks.



The alternative, of explicitly declaring the return type (in the(NSArray *)previous example) was a slight improvement, but is a Nnoying to write, and doesn ' t play nicely with subclasses.



This is where the compiler steps on to resolve this timeless edge case to the Objective-c type system:



instancetypeis a contextual keyword so can be used as a result type to signal that a method returns a related result type. For example:


 
 
@interface Person
+ (instancetype)personWithName:(NSString *)name;
@end

instancetype, unlikeid, can only is used as the result type in a method declaration.


instancetypewith, the compiler would correctly infer that the result of was an+personWithName:instance of aPerson.



Look-for-class constructors in Foundation-to-start using in the near futureinstancetype. New APIs, such as uicollectionviewlayoutattributes are usinginstancetypealready.


The following translation: Original address: http://blog.csdn.net/wzzvictory/article/details/16994913
First, what is Instancetype


Instancetype is clang 3.5, a keyword provided by clang that represents an unknown type of objective-c object returned by a method. We all know that an object of an unknown type can be represented by an ID keyword, so why is there another instancetype?


Ii. Association return type (related result types)


According to the naming rules of cocoa, the following rules are met:



1. In the class method, start with alloc or new



2. In the instance method, start with autorelease,init,retain or self



Returns an object of the class type of a method, known as a method that associates a return type. In other words, the return result of these methods is the type of the class in which the method is located, which is a bit around the mouth, see the following example:


[OBJC]View Plaincopy
    1. @interface NSObject
    2. + (ID) alloc;
    3. -(ID) init;
    4. @end
    5. @interface Nsarray:nsobject
    6. @end
When we initialize Nsarray using the following method:
[OBJC]View Plaincopy
    1. Nsarray *array = [[Nsarray alloc] init];
According to the Cocoa naming convention, the type of the statement[Nsarray alloc] is nsarray* because the return type of Alloc belongs to the associated return type. Similarly, the return result of[[Nsarray alloc]init]  is also nsarray*.




Third, Instancetype role 1, function


If a method is not associated with the return type, as follows:


[OBJC]View Plaincopy
    1. @interface Nsarray
    2. + (ID) constructanarray;
    3. @end





When we initialize Nsarray using the following method:


[OBJC]View Plaincopy
    1. [Nsarray Constructanarray];
According to the cocoa Method naming specification, the resulting return type is the same as the return type of the method declaration, which is the ID.





However, if you use Instancetype as the return type, as follows:


[OBJC]View Plaincopy
    1. @interface Nsarray
    2. + (instancetype) Constructanarray;
    3. @end
When initializing Nsarray in the same way:
[OBJC]View Plaincopy
    1. [Nsarray Constructanarray];
The resulting return type and method are the same type as the class, which is nsarray*!





To summarize, the Instancetype function is to make the methods of the non-associative return type return the type of the class!


2. Benefits


Being able to determine the type of an object can help the compiler better position code for us, such as:


[OBJC]View Plaincopy
    1. [[[Nsarray alloc] init] Mediaplaybackallowsairplay]; //"No visible @interface for ' Nsarray ' declares the selector ' Mediaplaybackallowsairplay '"
    2. [[Nsarray array] Mediaplaybackallowsairplay]; //(No error)
The first line of code in the example above, as  the result of [[Nsarray alloc]init] is nsarray*, This allows the compiler to detect whether the Nsarray implements the Mediaplaybackallowsairplay method based on the returned data type. Helps developers find errors during the compile phase. 





The second line of code, because the array does not belong to the associated return type method,[Nsarray array] Returns the ID type, and the compiler does not know whether an object of the ID type implements the Mediaplaybackallowsairplay method, will not be able to find fault for developers in time.


Iv. similarities and differences between Instancetype and ID 1, the same point


Can be used as the return type of a method


2, different points


①instancetype can return objects of the same type as the method's class, and the ID can only return objects of unknown type;



②instancetype can only be used as a return value, not as a parameter like an ID, as in the following notation:


[OBJC]View Plaincopy< param name= "wmode" value= "Transparent" >
    1. Err,expected a type
    2. -(void) SetValue: (instancetype) value
    3. {
    4. //do something
    5. }
Is wrong and should be written as:
[OBJC]View Plaincopy< param name= "wmode" value= "Transparent" >
    1. -(void) SetValue: (ID) value
    2. {
    3. //do something
    4. }


Instancetype and ID differences in OBJECTIVE-C


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.