UIButton创建时的一个坑
2014-11-17 02:04 Heisenbean 阅读(641) 评论(0) 编辑 收藏 举报UIButton的创建有两种方法:
方法一:
UIButton *button = [[UIButton alloc]init];
方法二:
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
这两种创建方式在MRC时代是有很大区别的,方法二创建的button系统是会自动释放其内存的,方法一就要手动释放了.
但是我这次说的重点不是这个,最近做项目,用button做了一个蒙版效果.当时自己是用方法二创建的,给这个button做了一个懒加载.
代码如下:
// // ViewController.m // button的weak和strong // // Created by Heisenbean on 14/11/6. // Copyright (c) 2014年 Heisenbean. All rights reserved. // #import "ViewController.h" @interface ViewController () @property (nonatomic,weak) UIButton *button; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; } -(UIButton *)button{ if (!_button) { _button = [UIButton buttonWithType:UIButtonTypeCustom]; _button.backgroundColor = [UIColor blackColor]; _button.alpha = .7f; _button.frame = [UIScreen mainScreen].bounds; [[UIApplication sharedApplication].keyWindow addSubview:_button]; [_button addTarget:self action:@selector(dismissBtn) forControlEvents:UIControlEventTouchUpInside]; } return _button; } - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { self.button.hidden = NO; } - (void)dismissBtn{ self.button.hidden = YES; } @end
我把蒙版添加到了window上,在模拟器上运行的时候是没有任何问题的.
但是在真机上,就会发现这个蒙版是没有的,debug之后发现这个button是nil.仔细看下会发现在给button声明属性的时候,用的是weak,改成strong就没问题了.但是如果button的属性是weak的时候模拟器是应该是会有长警告的,但是我写的时候是没有的.
我又重新写了一遍,发现了问题所有,用方法一创建button的时候,属性是weak的时候才会报警告,方法二创建的时候是不会有警告的.
那么对比一下,创建button的时候用方法一最为保险.
但是这里面的最根本的原因等我查完资料再做进一步的研究.
----------------分享是我的爱好,转载请标明出处----------------