The difference between id and instancetype in iOS

Associated return types and non-associated return types

  • Relevance return type

According to Cocoa's naming rules, methods that meet the following rules:
(1) In class methods, starting with alloc or new
(2) In instance methods, starting with autorelease, init, retain or self
will return an object of the class type where the method is located. , these methods are called methods with associated return types. In other words, the return result of these methods is of type the class in which the method is located.

For example:

@interface NSObject  
+ (id)alloc;  
- (id)init;  
@end

[NSArray alloc] and [[NSArray alloc]init] both return NSArray objects.

  • Non-associative return type
@interface NSArray  
+ (id)constructAnArray;  
@end


[NSArray constructAnArray];

According to Cocoa's method naming convention, the return type obtained is the same as the return type declared by the method, which is id.

But if you use instancetype as the return type, as follows:

@interface NSArray  
+ (instancetype)constructAnArray;  
@end
/

[NSArray constructAnArray];

At this time, the return type is the same as the method type.

The function of instancetype is to make methods with non-associated return types return the type of the class they are in!

The difference between the two

  • ID cannot determine the true type of the object during compilation.

    instancetype can determine the true type of an object during compilation.

  • If the return value of the init method is instancetype, then assigning the return value to another object reports a warning.

    If in the past, the return value of init was id, then no error would be reported if the object address returned by init was assigned to other objects.

  • ID can be used as a defined variable, as a return value, or as a formal parameter. But instancetype can only be used as a return value.

Guess you like

Origin blog.csdn.net/weixin_42357849/article/details/122602601
Recommended