Run Code At Start of Class

42 views Asked by At

For a class where I have an actual view attached, I can use viewDidLoad to handle any variables or constants I want to use. It will run before any other code in the method the moment the view becomes in use.

Is there something that does that for classes without views attached? For example, if I have a class called PDFCreator, when I create it like this:

PDFcreator *pdf = [[PDFcreator alloc] init];

Is there a way to run a function at that moment so that I can set those variables? Or some other way to encapsulate the data in that class?

2

There are 2 answers

1
Droppy On BEST ANSWER

Yeah, simply add any code to the init method:

@implementation PDFCreator

- (instancetype)init
{
    self = [super init];
    if (self) {
        _someInstanceVariable = @"Hello";
        _anotherInstanceVariable = 12;
    }
    return self;
}

This assumes your @interface PDFCreator looks something like this:

@interface PDFCreator : NSObject

@property NSString *someInstanceVariable;
@property (assign) int anotherInstanceVariable;

...
0
Justin On

You've identified the answer: override -init and perform the work there. Apple's documentation on object initialization may help you, here.