I came from a C# background where you initialize a class and then return itself like so
public class MyClass{
public int Id;
public string Name;
}
MyClass classInstance = new MyClass();
:
:
I know c# is different from objective c, but I'm trying to find a way to easily understand how objective c works to make the transition easier. And figure out best practices too.
Anyway, my question is why doyou have to create a method and return an "id" instead of returning it's own type? Like so:
- (id)initWithID:(NSInteger)id name:(NSString *)name
{
self = [self init];
if (self) {
self.ID = id;
self.name = name;
}
return self;
}
Thanks for your time
You return an object of type id
in initialization methods because of inheritance.
Think of it this way: You have an object of class Foo
. It has an init method called initWithWidgets
. Now, you create a subclass of Foo
and name it Bar
. By the rules of inheritance, it has access to the initWithWidgets
method. If the return type for initWithWidgets
was Foo
, then your Bar
class would be unable to use it to initialize itself! The return type would be different than the object you are trying to instantiate. Thus, if you use id
, you're saying "the return type of this object can be of any type" and you're safe for the subclasses!
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