2014/01/10

[iOS][Objective-C]deallocの挙動について

iOS5からARCがサポートされて、deallocメソッドを明示的に呼び出す必要性がなくなりました。

しかし、UINavigationController内部のUIViewControllerがpopされた時に、どうやらdeallocが呼び出されるようだ。

//AppDelegate.m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    ViewController *viewController = [[ViewController alloc] initWithNibName:nil bundle:nil];
    
    UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    self.window.backgroundColor = [UIColor whiteColor];
    self.window.rootViewController = navigationController;
    [self.window makeKeyAndVisible];
}
//ViewController.m
- (void)viewDidLoad
{
    [super viewDidLoad];

    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    button.frame = CGRectMake(100, 100, 200, 50);
    [button setTitle:@"next" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(pushed) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
}

-(void)dealloc{
    NSLog(@"呼ばれました");
}

-(void)pushed{
    ViewController *viewController = [[ViewController alloc] initWithNibName:nil bundle:nil];
    [self.navigationController pushViewController:viewController animated:YES];    
}
上のプログラムの場合、ナビゲーションバーに表示される「Back」ボタンによって、deallocメソッドがコールされました。

NSNotificationCenterのremoveObserverをかました時に便利かも。

0 コメント:

コメントを投稿