I have a class that inherits the MPMoviePlayerViewController
. I'm trying to rewrite the init
method so that I don't have to repeat code for every other -initWithSomething
function. For a custom initWithSomething method this will work. But I can't figure how to make it work for inherited iniWithSomething methods
-(instancetype)init
{
if(self = [super init]){
// This is code I don't want to repeat in initWithSomething methods
[self startWithHiddenControls];
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
[audioSession setActive:YES error:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self
name:UIApplicationDidEnterBackgroundNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(UIApplicationDidBecomeActive)
name:UIApplicationDidBecomeActiveNotification
object:nil];
}
return self;
}
-(instancetype)initWithContentURL:(NSURL *)contentURL
{
// Not overwriting doesn't use my overwriten init so i must do it.
// But how ?!?
// why [super init] makes inifinite loop? (I know the norm is [super <same method>])
if(self = [self init]){} // this will not work. Inifinite loop I believe.
return self;
}
//This method works fine
- (instancetype)initWithSettings:(NSDictionary *)settings
{
// [self init] works here but HOW?
if(self = [self init]){
//my custom stuff
}
}
During writin this post I found that [super init]
calls the -(instancetype)initWithContentURL:(NSURL *)contentURL
and there lies the infinite loop problem. Why the designated initializer init
calls the secondary initializer initWithURL
? Should it not be the other way around? Please explain.
Does this mean I should put my code, that I don't want repeated, in the initWithURL
method instead of the init
method.
Edit: And that is what I did. I entered the code in the initWithURL method. Now both the default init and my custom init will run it.
Why do you call
init
a designated initializer? I believe, it is not. Let's refer to the docs:So it doesn't seem to satisfy both characteristic: it has the least number of parameters and apparently it calls another initializer (
initWithContentURL
) withself
. So, I believe, if you found the real designated initializer, everything would work as expected.According to the MPMoviePlayerViewController class reference, the designated initializer is
initWithContentURL
. So you can simply override it instead ofinit
.