How can I create a class that doesn't have any special parent that calls a function when it is initiated?
Or does it not matter that I am using a UIViewController as a parent for a class that doesn't have a View Controller associated with it?
When you create a class, instead of using UIViewController which often comes up as the default super class while building iOS apps, change this to NSObject.
File -> New -> File... -> Cocoa Touch -> Objective-C Class -> Next -> ...
Give your class a name and choose NSObject from the subclass of dropdown.
Objective-C, unlike many other OOP languages, doesn't have constructors. Instead, everything that inherits from NSObject inherits an alloc method (which create memory space on the heap for the instance of the object) and a default init method.
You create instances of your object using [[MyObject alloc] init] by default, so if you override init and put code in here, it will execute when you run [[MyObject alloc] init]. You can create several different init methods, and you can even create factory methods. But the basic init override should look like this:
-(instancetype)init {
self = [super init];
if(self) {
//do stuff
}
return self;
}
But I prefer improving this further and writing a factory method so I don't have to type out [[MyObject alloc] init] every time. Factory methods should be paired with init methods that take the same arguments, and they'll look something like this:
+(instancetype)myObject{
return [MyObject alloc] init];
}
Now instead of doing:
MyObject *a = [[MyObject alloc] init];
You can just do this:
MyObject *a = [MyObject myObject];
This makes more sense with more complicated init methods. For example, consider:
MyDate *today = [[MyDate alloc] initWithYear:2013 month:11 day:14];
When we could just do:
MyDate *tday = [MyDate dateWithYear:2013 month:11 day:14];
And no matter how the initWithYear:month:day: method looks, the factory method would simply look like this:
+(instancetype)dateWithYear:(NSInteger) y month:(NSInteger)m day:(NSInteger)d {
return [[MyDate alloc] initWithYear:y month:m day:d];
}
init methods.super init, checking if(self), and return self;, but you can just follow that basic pattern and put whatever you want within the if block and you're good to go.
NSObject...init?NSProxy...