Search code examples
iosxcodeencapsulation

Run Code At Start of Class


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?


Solution

  • 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;
    
    ...