Objective-C init init method, how to avoid recursion?

I want to create a subclass of UINavigationController that always starts with the same root controller. Nothing special, so (for me) it makes sense to redefine the init method like this:

- (id) init {
   rootController = [[MyController alloc] init];

   if (self = [super initWithRootViewController:rootController]) {
       // do some more initialization
   }

   return self;
}

This obviously creates a problem because [super initWithRootViewController] will call [UINavigationController init], which of course is our overridden init method, so infinite recursion will occur.

I do not want to create an init method with a different name, for example, initCustom.

Currently, there is only one solution that I can come up with, but I really hate this kind of hack:

- (id) init {
   if (initCalled)
       return self;

   initCalled = YES;

   rootController = [[MyController alloc] init];

   if (self = [super initWithRootViewController:rootController]) {
       // do some more initialization
   }

   return self;
}

, : ? , - , .

EDIT: , , :

, . . , . ( , , ?)

+3
4

, UINavigationController .

, - initWithRootViewController:

- (id) initWithRootViewController:(UIViewController) viewController {
   return [super initWithRootViewController:[[[MyController alloc] init] autorelease]];
}

MyController, ...

+10

, , . Gcamp, UINavigationController.

, : , , :

@interface MyNavigationController : UIViewController {
   UINavigationController *navController;
   UIViewController *myController;
}

:

@implementation MyNavigationController

- (id) init {
   if (self = [super init]) {
       myController = [[MyController alloc] init];
       navController = [[UINavigationController alloc] initWithRootViewController:myController];
   }

   return self;
}

- (void) loadView {
   self.view = navController.view;
}

- (void) dealloc {
   [navController release];
   [myController release];
   [super dealloc];
}

@end

Objective-C, .

+4

? [super initWithRootViewController] overriden init? [super init], ( ) [UINavigationController init] ( overriden init).

+3

-initWithRootViewController: . nil

- (id) initWithRootViewController:(UIViewController*)ignored {
   rootController = [[MyController alloc] init];

   if (self = [super initWithRootViewController:rootController]) {
       // do some more initialization
   }

   return self;
}

: http://developer.apple.com/mac/library/documentation/cocoa/conceptual/ObjectiveC/Articles/ocAllocInit.html#//apple_ref/doc/uid/TP30001163-CH22-106376

+3

Source: https://habr.com/ru/post/1725411/


All Articles