开发者

Setting UINavigationController, old code?

开发者 https://www.devze.com 2023-01-21 07:19 出处:网络
I have been looking back at some old code from when I first started learning Objective-c and I have a quick question:

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 sam开发者_JAVA技巧e 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


Yep, your second code is definitely better than the first. However, I would change a few things. 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;
}   
0

精彩评论

暂无评论...
验证码 换一张
取 消