Search code examples
iosobjective-cinitializationclass-methodinstance-methods

iOS: Proper way of initializing an object?


Modeled after Parse's PFQuery class, I'm building my own EMQuery class, for my own project (not a subclass of PFQuery). My question is, if I want to perform a similar call to a class method in the manner that Parse does it (PFQuery *query = [PFQuery queryWith...]) would this be the correct approach?

+ (instancetype)queryWithType:(EMObjectType)objectType {
    EMQuery *query = [[self alloc] init];
    return [query initWithQueryType:objectType];
}

- (id)initWithQueryType:(EMObjectType)objectType {

    self = [super init];
    if (self) {

    }

    return self;
}

Solution

  • No - as you are calling init of the superclass twice.

    Your initWithQueryType should replace the call to init

    + (instancetype)queryWithType:(EMObjectType)objectType {
        EMQuery *query = [self alloc];
        return [query initWithQueryType:objectType];
    }
    

    The exception is if the init in your class does something. In that case the two inits init and initWithQueryType: should be set up that one calls the other and the one called is the only one that calls super init This one is the designated initialiser

    The main explanation of all initialization is the section on Object Initialization Apple document