Go Instancetype and ID differences in OBJECTIVE-C

Source: Internet
Author: User

There is one of the same two different. Same written by Mattt Thompson on Dec 10th, -Objective-C isA rapidly evolving language,inchA that's the You just Don'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 ThisInnovation isA result of Apple's philosophy of vertical integration. Just as Apple'S investmentinchDesigning its own chipsets gave them leverage to compete aggressively with their mobile hardware, so too have their investm EntinchLLVM 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 may has higher up with API design. One such example isInstancetype, the subject of ThisWeek's article.In Objective-C, conventions aren'T just a matter of coding best-practices, they is implicit instructions to the compiler.For example, Alloc and Init both hasreturnTypes ofID, yetinchXcode, the compiler makes all of the correct type checks. How is  ThisPossible?in Cocoa, there isA convention that methods with names like alloc, or Init alwaysreturnObjects that is an instance of the receiverclass. These methods is said to has a related result type. Class constructor methods, although they similarlyreturn ID, Don't get the same type-checking benefit, because they don't follow that naming convention. You canTry  This  out  forYourself:[[[nsarray alloc] init] mediaplaybackallowsairplay];// ? "No visible @interface for ' Nsarray ' declares the selector ' Mediaplaybackallowsairplay '"[[Nsarray array] mediaplaybackallowsairplay];//(No error)Because Alloc and init follow the naming convention forBeing a related result type, the correct type check against Nsarray isperformed. However, the equivalentclassConstructor array does not follow that convention, and isInterpreted as ID.ID  isUseful foropting- outof type safety, but losing it Dowant it sucks. The alternative, of explicitly declaring thereturnType ((Nsarray *)inchThe previous example) isA slight improvement, but isAnnoying to write, and doesn't play nicely with subclasses. This is whereThe compiler stepsinchTo resolve ThisTimeless Edge Caseto the objective-C type System:instancetype isA contextual keyword that can be used asa result type to signal that a method returns a related result type. For example:@interface Person+ (Instancetype) Personwithname: (NSString *) name;@endInstancetype, unlikeID, can only be used asThe result typeincha method declaration. With Instancetype, the compiler would correctly infer that the result of+personwithname: isAn instance of a Person.look for classConstructorsinchFoundation to startusingInstancetypeinchThe near future. New APIs, such asUicollectionviewlayoutattributes isusingInstancetype already. The following translation: Original address: http://blog.csdn.net/wzzvictory/article/details/16994913first, what is Instancetypeinstancetype is clang3.5 begins, Clang provides a keyword that represents an unknown type of objective-returned by a methodThe C object. We all know that an object of an unknown type can be represented by an ID keyword, so why is there another instancetype? The associated return type (related result types) satisfies the following rules according to the naming rules of cocoa:1, class method, starting with alloc or new2, an instance method, starting with Autorelease,init,retain or self, returns an object of the class type of the method that is referred to as the method that is associated with the 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 of a detour, see the following example: [OBJC] View plaincopy on code to see a snippet derived from my Code slice@interfaceNSObject+ (ID) Alloc; - (ID) init; @end            @interfaceNsarray:nsobject@endWhen we initialize the Nsarray using the following method: [OBJC] View plaincopy on code to see a snippet derived from my Code slice 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, [[Nsarray Alloc]init] Return results are also nsarray*. Iii. the role of Instancetype1, action if a method that is not associated with the return type is as follows: [OBJC] View plaincopy on code to see a snippet derived from my Code slice@interfaceNsarray+ (ID) Constructanarray; @endWhen we initialize the Nsarray using the following method: [OBJC] View plaincopy on code to see the chip derivation to my Code slice [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 on code to see a snippet derived from my Code slice@interfaceNsarray+(instancetype) Constructanarray; @endWhen initializing the Nsarray in the same way: [OBJC] View plaincopy on code to see the snippet derived from my Code slice [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, the benefit can determine the type of object, can help the compiler to better locate the code for us to write problems, such as: [OBJC] View plaincopy code on the view of the chip derivation to my Code slice [[[[[[Nsarray alloc] init] Mediaplaybackallowsairplay]; //"No visible @interface for ' Nsarray ' declares the selector ' Mediaplaybackallowsairplay '"[[Nsarray array] mediaplaybackallowsairplay];//(No error)The first line of code in the example above, as the result of [[Nsarray Alloc]init] is Nsarray*so that the compiler can detect whether 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, the compiler does not know whether an object of the ID type implements the Mediaplaybackallowsairplay method, and it is not possible for developers to find errors in time. Iv. similarities and differences of Instancetype and IDs1, the same point can be used as the return type of the method2, ①instancetype can return an object of the same type as the method's class, the ID can only return an object of an unknown type; ②instancetype can only be returned as a return value, not as a parameter like an ID, as in the following notation: [OBJC] View Plaincopy on code to see a snippet derived from my Code slice//err,expected a type- (void) SetValue: (instancetype) value {//Do something} is wrong and should be written as: [OBJC] View plaincopy on code to see a snippet derived from my Code slice- (void) SetValue: (ID) Value {//Do something}

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