Search code examples
iosobjective-cnsmutableurlrequeststatic-initializer

Overriding a NSMutableUrlRequest static initializer?


Heres my scenario. Most of my network calls now need to have an api key inserted into the header field when making a request. So what i was thinking i could do was make a category of NSMutableUrlRequest. Override one of the initalizers. Then in that one initializer i could set the api key as a header field. So everytime i create an object of NSMUTABLEURLREQUEST the header field i need is already set. If you look at the apple doc here NSMutableUrlRequest you can see that the object has 4 initializers 2 class and 2 instance methods. Ill list my questions

  1. What initializer function should i override in order to complete my task? The class or the instance ones?
  2. How can i override it? Either if its an instance or class initializer?
  3. Is this even a good way to go about it? or should i just subclass it and override it like that?

My code has been written for sometime now and well i dont want to go back and insert the api key into each individual request because well theres a lot of them. In a way i think this is a better approach to it because ill just have to set the apiKey in one place and not many place, which lessens the probability of a programming errors.Thank you for your help.

P.S. Even if this isnt a good way to complete this can someone still show me how a class initializer works? Like whats the underlying code so i can generate my own static class initializers also. Each time i try to override the class method i cant figure out what type to return.

Thank you for your help


Solution

  • Categories are not meant to be used to override. You use categories when you want to add additional functionality to existing classes. If you really want to override the initializers then use inheritance.

    The static functions are not initializers, they are just helper functions that creates the instance for you, so there's no need to handle them. The simple initWithURL: method is just a simplified version which provide default values for the designated initializer initWithURL:cachePolicy:timeoutInterval:; so in your subclass you actually only need to override this single initializer, looking something like this:

    @interface MyNSMutableURLRequest : NSMutableURLRequest
    @end
    
    @implementation MyNSMutableURLRequest
    
    - (instancetype)initWithURL:(NSURL *)URL cachePolicy:(NSURLRequestCachePolicy)cachePolicy timeoutInterval:(NSTimeInterval)timeoutInterval {
        self = [super initWithURL:URL cachePolicy:cachePolicy timeoutInterval:timeoutInterval];
        if (self) {
            //do your stuff here
        }
        return self;
    }