1

Possible Duplicate:
What is the meaning of id?

I am the newbie to Ios programming.

I saw the following declaration

- (id)init

what does (id) mean here?

Community
  • 1
  • 1
user496949
  • 83,087
  • 147
  • 309
  • 426

4 Answers4

6

id denotes a type which is compatible with any object. The notation

- (id)init

means the init instance method of your class; typically it's used to initialize the instantiated object after memory allocation (usually done using alloc). In Objective-C, methods' return type is declared by putting the type in parentheses before the method name. So, here it means that the init method may return any Objective-C object.


But you should really, really google an Objetive-C tutorial and read it. This is such a fundamental thing for which there is no excuse for not reading a tutorial or other documentation.

1

id is the plain C compatible type that represents an Objective-C object. This allows C source code to store, and interact with, Objective-C objects.

Chris Becke
  • 34,244
  • 12
  • 79
  • 148
0

The reason for it to be of type 'id' is that the -init method is inherited all the way up from NSObject (in objective-C you can not overload methods, hence you can not change the argument/retrurn value types when subclassing). Since 'id' works with any object, this is OK.

EDIT It seems that specifying a concrete class as the return type of -init is OK, even though you are ultimately overriding '-[NSObject init]'.

I guess the use of 'id' is just a custom?

The fact that 'id' acts as a "generic Objective-C object pointer" that accepts any object type on assignment remains unchanged, though.

Nicolas Miari
  • 16,006
  • 8
  • 81
  • 189
  • 2
    You can indeed change the classes of return and argument types when subclassing. – jscs Jul 07 '12 at 08:07
  • "you can not change the argument/retrurn value types when subclassing" This is not true, actually. Haven't you seen things like `- (MyViewController *)init`? –  Jul 07 '12 at 08:11
  • You are right, I stand corrected. What I'm sure you can not do is subclass a property accessor with one specifying a subclass of the original type. (but of course that is not relevant to the question) – Nicolas Miari Jul 07 '12 at 08:42
  • ...So, why do we keep using 'id' over and over, again? :) – Nicolas Miari Jul 07 '12 at 08:45
  • Additionally, this article: http://www.techotopia.com/index.php/Objective-C_Inheritance seems to validate my initial claim... So which one is it? – Nicolas Miari Jul 07 '12 at 09:05
-1

-(id)init is called to initialize the variables inside an object and do any necessary setup (it's basically the constructor).

A possiable duplication can be What's the -(id)init method good for?

Community
  • 1
  • 1
Jigar Pandya
  • 6,004
  • 2
  • 27
  • 45