Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Objective-C why is id used as return type for init methods?

Tags:

objective-c

I did some quick searching and couldn't find an answer for this.

I'm interested to know why in Objective-C, id is used as the return type for init methods.

My guess is that it's because if the class is overridden, you don't want to return an object of the superclass's type, but I'm interested to know if it's done for some other reason.

like image 331
Ben Baron Avatar asked Dec 23 '11 06:12

Ben Baron


People also ask

What is ID type in Objective C?

id is the generic object pointer, an Objective-C type representing "any object". An instance of any Objective-C class can be stored in an id variable.

What is the default return type in Objective C?

(id) is the default return type if none is given.

How do you call an init method in Objective C?

Whenever an object is "created" by default it is supposed to be done with myObject=[[MyObjectClass alloc]init] or the equivalent shortcut myObject=[MyObjectClass new] . That is where your init method is called.


1 Answers

Yup. Your idea is right on the money. A subclass should still be able to use its superclass's initialization methods and return its own type instead of the super type and returning id allows it to do that.

like image 104
Sean Avatar answered Oct 06 '22 01:10

Sean