Some unusual operations in iOS

Posted by fukas on Sat, 07 Dec 2019 12:13:24 +0100

1. Grammar sugar

The following code

  NSString *str = nil;
    
    NSDictionary *safeDic = [NSDictionary dictionaryWithObjectsAndKeys:@"value",@"key",str,@"key1", nil];
    
    NSLog(@"%@",safeDic?:@"Dictionary is not safe");
    
    NSDictionary *dic = @{@"key":str};
    
    
    NSLog(@"%@",dic);

Two of them are used:

1. Dictionary shape is dic = @ {};

2. Three item operator a?:b;

Normally, we may have to write a lot of code, but after the lexical sugar, we will omit a lot of code. However, when the code above runs, it is found that the first dictionary, that is, normal native writing, is normal, while the second dictionary, will crash,,,

In addition, when we initialize the relevant UI controls, it may look like this:

@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];

It can be written in French

 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;
    });

Topics: Mobile