views:

33

answers:

1

I have been looking back at some old code from when I first started learning Objective-c and I have a quick question:

// THIS IS MY OLD CODE
@implementation syntax_UINavAppDelegate
@synthesize window;
@synthesize navController;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    UITableViewController *rootController = [[UITableViewController alloc] init];
    navController = [[UINavigationController alloc] initWithRootViewController:rootController];

    [window addSubview:[[self navController] view]];
    [window makeKeyAndVisible];
    return YES;
}

my current understanding is that in the above code there are two issues, firstly I am acessing the property navController directly (I should be using the setter) and secondly do I have a memory leak with [UINavigationController alloc]? My gut feeling is that its not a leak as it will get released when I call [navController release]; in dealloc, BUT that its just messey and a bad way to do things. Here is my (now I know a little more) rework of the same code.

// NEW CODE
@implementation syntax_UINavAppDelegate
@synthesize window;
@synthesize navController;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    UITableViewController *rootController = [[UITableViewController alloc] init];
    UINavigationController *tempController = [[UINavigationController alloc] initWithRootViewController:rootController];
    [self setNavController:tempController];
    [rootController release];
    [tempController release];

    [window addSubview:[[self navController] view]];
    [window makeKeyAndVisible];
    return YES;
}   

just curious ...

Gary

+1  A: 

Yep, you second code is definitely better than the first. However, I would change a few thins. Skip the tempcontroller, instead assign it directly to navController using dot notation. Make sure you call [navController release] in dealloc though.

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    UITableViewController *rootController = [[UITableViewController alloc] init];
    [self.navController =  [[[UINavigationController alloc] initWithRootViewController:rootController] autorelease];
    [rootController release];

    [window addSubview:self.navController.view];
    [window makeKeyAndVisible];
    return YES;
}   
Rengers
thank you very much, personally I prefer to release the alloc myself and then let the dealloc release the retain in the property (but thats just my preference) thank you for taking the time to post, much appreciated.
fuzzygoat