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
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.
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 .
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.
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 ( . )
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With