While your code is in order, I would structure the init calls in reverse order, where the assigned initializer is the most verbose, and the more general ones will be the default bubbles:
-(id) initWithID:(NSInteger)id CarYear:(NSString *)year { if(self = [super init]) { _year = year; _id = id; } return self; } -(id)initWithID:(NSInteger)id { return [self initWithID:id CarYear:@"unset"]; } -(id)init { return [self initWithID:0]; }
if calling one of the more general initializers will result in an illegal state, you can throw an error instead to prohibit its use.
Suppose a car must have an identifier, but not a year. It would be nice to use initWithID , but using init will result in an inconsistent state, so we want to force it not to be used:
-(id)init { [NSException raise:NSInternalInconsistencyException format:@"You must use -initWithID: or -initWithID:CarYear:", NSStringFromSelector(_cmd)]; return nil; }
- In this code, self is set 3 times. Is there a better solution?
see above
- Do I have a memory leak in this code? (using ARC)
No, everything is okay
- Do I need to check if there is always (self = ...) or redundant code?
As I showed you: you can call different init methods in a chain. only the last in this chain should accomplish this.
-(id) initWithID:(NSInteger)id CarYear:(NSString *)year { if (self = [super init]) { [self setIsCurrentCar:NO]; [self setID:id]; [self setCarYear:year]; } return self; }
You should not use seters on self in init methods, see Apple docs .
source share