The difference between instance and ID

Source: Internet
Author: User

Instancetype clang 3.5 Provides a keyword that indicates that a method returns an OC object of an unknown type

Know the ID any type of keyword, why do you still see a new keyword?

Return Association Type

1, class method, Alloc, New start

2. Autorelease,init,retain,self start in instance method

An object that returns the type of the class in which the method is located, that is, the method that associates the return type.

The return result of these methods is the type of the class in which the method resides.

For example

@interface NSObject

+ (ID) alloc;

-(ID) init;

@end

When we initialize Nsarray,

Nsarray*array = [[Nsarray alloc] init];

[Nsarray alloc] return type belongs to the associated return type, Nsarray *

Instancetype

If a method is not associated with the return type

@interface Nsarray

+ (ID) Constructanarray;

@end

When we initialize,

[Nsarray Constructanarray]

The return type that gets the return type and method declaration is the same as the ID

If you use Instancetype as the return type

@interface Nsarray

+ (instancetype) Constructanarray;

@end

Same-mode initialization

[Nsarray Constructanarray]

The resulting return type and method are the same type, which is Nsarray *

The function of Instancetype is to make the methods of the non-associative return types return the type of the class in which they are located!

Benefit: Determining the object type helps the compiler to better locate code issues.

Same point:
The return type as a method

Different points:
1. Instancetype can return an object of the same type as the method's class, and the ID can only return an object of unknown type.

2, Instancetype can only be used as the return value, ID can be used as parameter.

-(void) SetValue: (instancetype) value

{

}

Error!

should be written

-(void) SetValue: (ID) value

{

}

The difference between instance and ID

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.