您的位置:首页 > 移动开发 > IOS开发

IOS之从storyBoard生成的controller对象的生命周期问题

2014-09-04 19:56 260 查看
假设在storyBoard中共有两个控制器。 

1.rootViewController :根控制器

 2.testViewController: 测试用的控制器,它的storyBoardID设置为test

根控制器中得代码:

#import "rootViewController.h"
#import "testViewController.h"

@interface test1ViewController ()
{
testViewController *test; //测试控制器
}
@end

@implementation rootViewController

...

//根控制器添加的按钮方法,点击按钮,就会弹出测试控制器界面
- (IBAction)buttonTapped:(id)sender
{
//用storyBoard的方法生成对象
test=[self.storyboard instantiateViewControllerWithIdentifier:@"test1"];

//动态显示出来
[self presentViewController:test animated:YES completion:NULL];

//打印出对象在内存中的地址
NSLog(@"%p",test);
}

//当测试控制器消失时用于检测test对象是否被系统回收。
- (IBAction)showTestRetainCount:(id)sender
{
NSLog(@"%d",[test RetainCount]);
}

@end


测试控制器中代码:

@implementation testViewController

//添加一个返回按钮响应方法
- (IBAction)buttonTapped:(id)sender
{
[self dismissViewControllerAnimated:YES completion:^{
//当界面消失后打印出自己本身的引用计数,此时该对象虽然不在界面显示,但还没有被系统回收,引用计数不为0
NSLog(@"%d",[self retainCount]);
}];
}
@end


结论:

  每次显示出的测试控制器对象的内存地址都不一样,这证明每次都会生成新的对象。

  而当测试控制器消失时,在显示它的引用计数,则程序直接崩溃,证明test对象所占用的内存已被系统回收。

  由此可知:test对象由[self.storyboard instantiateViewControllerWithIdentifier:@"test"]这个方法诞生。

       在[rootViewController presentViewController:test animated:YES completion:NULL];这个方法显示出来。

       最终由[self dismissViewControllerAnimated:YES completion:NULL];这个方法结束生命周期,test对象被系统回收。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐