由于以前看过外包的奇葩app,一个简单的app,几个viewcontroller居然可以内存飙到将近100M,简直是不忍直视,所以从那开始,自己每次写的代码,都会看,当控制器pop后是否会调delloc,或者看xcode的内存显示,严格要求自己。
typedef NS_ENUM(NSInteger, Direction) {
leftDirection = 0,
rightDirection,
};
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
self.page = 0;
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
/////////////1.///////////////
NSArray *colors = @[[UIColor redColor],[UIColor orangeColor],[UIColor purpleColor]];
_scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 400)];
_scrollView.pagingEnabled = YES;
_scrollView.showsHorizontalScrollIndicator = NO;
_scrollView.showsVerticalScrollIndicator = NO;
float _x = 0;
for (int i = 0; i < colors.count; i++) {
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0+_x, 0, 320, 400)];
view.backgroundColor = colors[i];
[_scrollView addSubview:view];
_x += 320;
}
_scrollView.contentSize = CGSizeMake(_x, 0);
[self.view addSubview:_scrollView];
///////////////2.//////////////////
_timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(changeView) userInfo:nil repeats:YES];
}
-(void)changeView
{
//修改页码
if (self.page == 0) {
self.switchDirection = rightDirection;
}else if(self.page == 2){
self.switchDirection = leftDirection;
}
if (self.switchDirection == rightDirection) {
self.page ++;
}else if (self.switchDirection == leftDirection){
self.page --;
}
[_scrollView setContentOffset:CGPointMake(320*self.page, 0) animated:YES];
}
下面是容易忽略的部分,但是很重要,一旦不调用下面的方法,就算你的控制器pop了,也不会走delloc,你可以试试。
-(void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
[_timer invalidate];
}