views:

43

answers:

2

I am just curious with regards to the correct way to create a view controller programatically. When I compile this code with the static analyser I get a leak (as you would expect) from the alloc. Should I just leave it as it needs to stay until the app exits anyways, or is there a cleaner way?

- (BOOL)application:(UIApplication *)application
        didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    

    NSLog(@"UIApplication application:");
    RectViewController *myController = [[RectViewController alloc] init];
    [window addSubview:[myController view]];
    [window makeKeyAndVisible];
    return YES;
}

cheers Gary

+2  A: 

Keep a reference to the view controller in you app delegate (instance, property, synthesize and release in dealloc).

And then instantiate it like this:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    

  NSLog(@"UIApplication application:");

  RectViewController *rootControllerTemp = [RectViewController new];
  self.rootController = rootControllerTemp;
  [rootControllerTemp release];

  [window addSubview:[self.rootController view]];

  [window makeKeyAndVisible];

  return YES;
}
Michael Kessler
typing that same thing! beat me to it! LOL
slf
Thank you, much appreciated Michael.
fuzzygoat
+2  A: 

In this case, keep a reference to your view controller as an instance variable on the AppDelegate and release it in the AppDelegate's dealloc method.

@interface AppDelegate : NSObject {
    // ...
    RectViewController *myController;
}

// ...
@end


@implementation AppDelegate

// ...

- (BOOL)application:(UIApplication *)application
        didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    

    NSLog(@"UIApplication application:");
    myController = [[RectViewController alloc] init];
    [window addSubview:[myController view]];
    [window makeKeyAndVisible];
    return YES;
}

- (void) dealloc {
    // ...
    [myController release];

    [super dealloc];
}

// ...

@end
Will Harris
Thanks Will, just what I was after.
fuzzygoat