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

意思就是 不確定

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