UIButton创建时的一个坑

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的时候用方法一最为保险.

但是这里面的最根本的原因等我查完资料再做进一步的研究.

转载于:https://www.cnblogs.com/botheast/p/4102774.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值