What is the (id) mean in the init method? [duplicate] - objective-c

This question already has answers here:
Closed 10 years ago.
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?

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.

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.

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.

-(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?

Related

what does id <SampleProtocolDelegate> _delegate mean in objectiveC [duplicate]

This question already has answers here:
Explaning syntax for #property id<delegateName>
(3 answers)
Closed 7 years ago.
I am currently in the process of learning ObjectiveC.
I wanted to know what the following statement means
id <SampleProtocolDelegate> _delegate;
I got this from here
I know that id is the type but what is <SampleProtocolDelegate> ?
The type is not id, the type is id <SampleProtocolDelegate>. Which effectively means _delegate is a reference to an object which implements the protocol of type SampleProtocolDelegate.
If you don't know fully what a delegate is and the delegate pattern then read up about them then come back to the code later.
A delegate is not something specific to Objective-C, a delegate is a common pattern in many languages.
What is specific to Objective-C is that id <SampleProtocolDelegate> is Objective-C's syntax for declaring the reference to the object implementing the SampleProtocolDelegate "protocol" i.e. its API.
If my explanation is confusing, just read up about the delegate pattern from a high level point of view first.
<SampleProtocolDelegate> means that the object (_delegate) conforms to the SampleProtocolDelegate.
I.e. it implements the required methods of the protocol.
"SampleProtocolDelegate" is a protocol.
A protocol is a list of method declarations. If your class adopts the
protocol, then you have to implement those methods in your class.
https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/WorkingwithProtocols/WorkingwithProtocols.html#//apple_ref/doc/uid/TP40011210-CH11-SW1
"_delegate" is object of some class that conforms to "SampleProtocolDelegate" protocol.

Use of "Self" keyword in Objective-C [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Objective-C - When to use ‘self’
I can't understand very well the importance and the usage of the "self" keyword in objective-c. It's my first OOP language so i got stuck on some concepts.
When i should use "self"? Why is it useful?
Thanks for the answers!
Edit: I can't understand why is this a duplicated post of Objective-C - When to use 'self' when there there is not the explanation of "Self" that i wanted.
self is a special variable in Objective-C, inside an instance method this variable refers to the receiver(object) of the message that invoked the method, while in a class method self will indicate which class is calling.
self refers to the actual object that is executing the current method, it is an invisible argument passed automatically by the runtime environment to your instance methods.

Objective-C method overriding/overloading confusion

There seems to be some debate/disagreement on whether it is possible to 'overload' methods in Objective-C. Putting aside that it is impossible to define method overloading in Objective-C is terms equal to those of C++ (because of method signature syntax differences), I would ask in particular: Which of the following is allowed and which are not?
1) A class declaring/implementing both these methods:
- (void) doSomethingWithObject:(ClassA*) object;
- (void) doSomethingWithObject:(ClassB*) object;
2) A class declaring/implementing both these methods:
- (void) doSomethingWithObject:(ClassA*) object;
- (BOOL) doSomethingWithObject:(ClassA*) object;
3) A class declaring/implementing this method:
- (void) doSomethingWithObject:(ClassB*) object;
...when its superclass declares/implements this method:
- (void) doSomethingWithObject:(ClassA*) object;
(and the analogue for conflicting return value), both when A) ClassB descends from ClassA, and B) Not.
Question 1: no can do: Objective-C doesn't include the types in the method names; there is no mangling. It might work with Objective-C++ -- never used it that much.
Question 2: Same. Won't work.
Question 3: Will work.
EDIT: in general, method names do not include any types, so if you strip the types and they are the same then it will be considered the same, and therefore won't be allowed in the same class. Along the same lines, it WILL work if it's in different classes, although you might get some confusion if the types used in the call and the types used in what gets called don't quite agree.
You are thinking in terms of C++ where the compiler does the static binding of figuring out which instance method to call based on the type of the input.
Objective-C doesn't work that way. Instead, all binding is dynamic at run-time. Kinda like all methods being declared "virtual" in C++. The programmer is responsible for passing in appropriate variables that respond in the way your method expects.
Your method could query the object being passed in whether it responds to certain selectors and take appropriate action based on that if you wanted more robust behavior. Or your method could ask the object being passed in whether it is a type it expects. Again, this would all be done at run-time in your method. Not by the compiler.
So the answer is, declare as:
- (void) doSomethingWithObject:(id) object;
... then pass in whatever object you like.

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

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.
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.
The superclass type idea, while a good theory, doesn't really stand up: A NSString * is a NSObject *. There's no reason it can't be referred to as such.
Instead, I think it has more to do with function signatures. In a dynamic language like Objective-C, you can have no idea what class you're messaging. But the compiler must know what type is being returned. That and Objective-C's history of convention-based programming (rather than having strict rules) means that your subclass could return a NSRect (a struct) or NSInteger (a scalar) from init. It was kooky, but valid.
C++ has a similar problem, see Is the return type part of the function signature?.
So we needed a single type for all methods with a signature of -(id)init, and id was the only thing that made sense as it specified only that the return type was an instance. That's enough for the compiler to do the right thing. Now we have instancetype, which matches the class being messaged.
In the meantime Apple added a new way to declare the return type of init methods.
It is instancetype. Read more about it e.g. here
it's possible for init to actually return an instance of a different class, so id is used. can't say i've ever seen this happen in practice, but hey :)

When to use [self.obj message] vs [obj message] [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicates:
When to access properties with 'self'
In Objective-C on iOS, what is the (style) difference between “self.foo” and “foo” when using synthesized getters?
For example sake, I have a #property named obj and I #synthesize it. So when do I need to use [self.obj message] vs [obj message] in my implementation class.
Using self, the getter method will be called. Thus, any additional logic in this getter method is executed. This is especially useful when instance variables are lazy loaded through their getters.
I myself try to use self most of the time. Lazy loading is just an example, another thing is that with self, subclasses may override the getter to get different results.
Using self to set a variable is even more useful. It will trigger KVO notifications and handle memory management automatically (when properly implemented, of course)
Here are two great tutorials that cover this issue well:
Understanding your (Objective-C) self
When to use properties & dot notation
When synthesize a property, the compiler declare a related ivar for you, in default, the ivar is the same as property name. I recommend use self.obj always to keep code cleaner, and avoid some potential bugs.
And I suggest you follow the good practice from Apple, #synthesize obj=_obj, the ivar will become _obj, when you mean to use property, this style force you to write self.obj, directly call obj will be error since the ivar is _obj.
Edit: automatically creating ivar for property is only in modern Objective-C runtime, it's safe in iOS SDK 4.0 and Mac OS X 10.6 above.
http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjectiveC/Chapters/ocProperties.html%23//apple_ref/doc/uid/TP30001163-CH17-SW1
For #synthesize to work in the legacy
runtime, you must either provide an
instance variable with the same name
and compatible type of the property or
specify another existing instance
variable in the #synthesize statement.
With the modern runtime, if you do not
provide an instance variable, the
compiler adds one for you.
In the future, please search the site. You'll often find that the exact question you're asking has been asked before:
difference between accessing a property via "propertyname" versus "self.propertyname" in objective-c?
When to access properties with 'self'
self.variable and variable difference
Objective-C: When to call self.myObject vs just calling myObject
iVar property, access via self?
Should I Use self Keyword (Properties) In The Implementation?
In Objective-C on iOS, what is the (style) difference between "self.foo" and "foo" when using synthesized getters?
When to use self on class properties?
... etc.