Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is main difference between "auto" and "instancetype" type?

What is difference between auto and clang type instancetype?
Where we have to use auto and where we have to user instancetype?

like image 669
virus Avatar asked Feb 27 '14 07:02

virus


People also ask

What is auto variable type?

In computer programming, an automatic variable is a local variable which is allocated and deallocated automatically when program flow enters and leaves the variable's scope. The scope is the lexical context, particularly the function or block in which a variable is defined.

What is Auto in Objective C?

auto in Objective C is inherited from C and means auto keyword. Defines a local variable as having a local lifetime. Keyword auto uses the following syntax: [auto] data-definition; As the local lifetime is the default for local variables, auto keyword is extremely rarely used.


1 Answers

auto in Objective C is inherited from C and means auto keyword

Defines a local variable as having a local lifetime.

Keyword auto uses the following syntax:

[auto] data-definition; As the local lifetime is the default for local variables, auto keyword is extremely rarely used.

Note: GNU C extends auto keyword to allow forward declaration of nested functions.

If you are looking for equivalent for C++11's auto or C#'s var - in Objective C id is used.

id a = [NSString new];
id b = [NSNumber new];

But id is not resolved to concrete type at compile time like auto in C++11 does.

instancetype is a contextual keyword that 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, unlike id, can only be used as the result type in a method declaration.

With instancetype, the compiler will correctly infer that the result of +personWithName: is an instance of a Person. And will generate an error if you will try to call

[[Person personWithName:@"Some Name"] methodThatNotExistsInPerson];

If you will use id compiler will not do so, you will not fix it and will receive runtime error!

Instancetype is used to add a little more "strong typing"to Objective C.

like image 98
Avt Avatar answered Nov 15 '22 15:11

Avt