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
idin initialization methods because of inheritance.Think of it this way: You have an object of class
Foo. It has an init method calledinitWithWidgets. Now, you create a subclass ofFooand name itBar. By the rules of inheritance, it has access to theinitWithWidgetsmethod. If the return type forinitWithWidgetswasFoo, then yourBarclass 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 useid, you’re saying “the return type of this object can be of any type” and you’re safe for the subclasses!