iOS中的一些不很常见的操作

1、语法糖

以下代码

  NSString *str = nil;
    
    NSDictionary *safeDic = [NSDictionary dictionaryWithObjectsAndKeys:@"value",@"key",str,@"key1", nil];
    
    NSLog(@"%@",safeDic?:@"字典不安全");
    
    NSDictionary *dic = @{@"key":str};
    
    
    NSLog(@"%@",dic);

其中,用到了两个:

1、字典形如 dic = @{};

2、三目运算符 a?:b;

正常我们可能要写一大堆的代码,但是用语法糖之后,就会省略很多,但是上边的代码运行发现,第一个字典,即正常原生写法,是正常的,而第二个字典,则会崩溃,,,

还有正常我们初始化相关UI控件的时候可能是这样子:

@property (nonatomic , strong) UIImageView *imageView;
@property (nonatomic , strong) UILabel *lable;
- (UIImageView *)imageView{
    
    if (!_imageView) {
        
        _imageView = [[UIImageView alloc]init];
        _imageView.backgroundColor = UIColor.redColor;
        _imageView.frame = CGRectMake(200, 100, 50, 50);
        [self.view addSubview:_imageView];
    }
    return _imageView;
}
self.lable = [[UILabel alloc]initWithFrame:CGRectMake(100, 300, 80, 80)];
    self.lable.text = @"asdfgh";
    self.lable.font = [UIFont systemFontOfSize:14];
    self.lable.textColor = [UIColor redColor];
    [self.view addSubview: self.lable];

用语法糖的话可以这么写

 self.imageView = ({
        UIImageView *imageview = [[UIImageView alloc]init];
        imageview.backgroundColor = UIColor.redColor;
        imageview.frame = CGRectMake(200, 100, 50, 50);
        [self.view addSubview: imageview];
        imageview;
    });
    
    self.lable = ({
        
        UILabel *lable = [[UILabel alloc]initWithFrame:CGRectMake(100, 300, 80, 80)];
        lable.text = @"asdfgh";
        lable.font = [UIFont systemFontOfSize:14];
        lable.textColor = [UIColor redColor];
        [self.view addSubview: lable];
        lable;
    });

2、iOS9的几个新关键字(nonnull、nullable、null_resettable、__null_unspecified)

  • nonnull
///不能为空字段 三种样式
@property (nonatomic , strong , nonnull) NSString *nuStr;
@property (nonatomic , strong) NSString * _Nonnull nustr1;
@property (nonatomic , strong) NSString * __nonnull nustr2;

这样子用到这几个属性的时候,就会有提示

其实很多系统的都会有这种提示,指示平时没注意。。。

还可以用到方法中:

- (nonnull NSString *)cannotnil:(nonnull NSString *)notnilStr;

这样子就会有

  • nullable
///可以为空 三样式
@property (nonatomic , strong , nullable) NSString *abStr;
@property (nonatomic , strong) NSString * _Nullable abStr1;
@property (nonatomic , strong) NSString * __nullable abStr2;

提示和上边是一样的

 

  • null_resettable

意思就是必须重写set 不为空

  • null_unspecified

意思就是 不确定

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章