Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Purpose of 'instancetype' keyword in 'objectWith' methods? [duplicate]

Tags:

objective-c

Recent Objective-C compilers introduce the 'instancetype' keyword, which among other things can be used to provide typed collections. . .

I saw another purpose of instancetype, which was using it in 'objectWith' type methods on classes. For example:

@interface Car

    +(instancetype)carWithWheels:(NSArray*)wheels;

@end

The justification was that the compiler will do type checking for initWith methods, but not for 'objectWith' methods.

Besides being potentially easier to type, what is the benefit of using 'instancetype' in place of the actual class-name? Eg:

@interface Car

    +(Car*)carWithWheels:(NSArray*)wheels;

@end
like image 873
Jasper Blues Avatar asked Apr 23 '13 06:04

Jasper Blues


People also ask

What is the purpose of an object's instance variables?

An instance variable reserves memory for the data your class needs. Let's assume you want to add a place for a string or int variable. You can use an instance variable to reserve that memory for the lifetime of the object. Each object will receive unique memory for its variables.

Why do we need to use the this keyword in our instance methods?

Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this .

What is the purpose benefit of using instance variables and methods in a class?

Instance variables are specific to a particular instance of a class. For example, each time you create a new class object, it will have its copy of the instance variables. Instance variables are the variables that are declared inside the class but outside any method.

What is the purpose of an object's instance variables Python?

Instance variables are used within the instance method. We use the instance method to perform a set of actions on the data/value provided by the instance variable. We can access the instance variable using the object and dot ( . )


1 Answers

By using instancetype, you're saying that subclasses will return an object of the subclass.

If we have

@interface Car

    +(instancetype)carWithWheels1:(NSArray *)wheels;
    +(Car *)carWithWheels2:(NSArray *)wheels;

@end

and

@interface VolkswagenBeetle : Car

@end

then +[VolkswagenBeetle carWithWheels1:] is guaranteed to return an instance of VolkswagenBeetle; but +[VolkswagenBeetle carWithWheels2:] might return a Buick, a Caddilac, or a ChittyChittyBangBang.

like image 61
Simon Avatar answered Oct 15 '22 21:10

Simon