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

本文深入探讨了编程中的语法糖概念,特别是在Objective-C中如何简化代码,并介绍了iOS9引入的新关键字,如nonnull、nullable等,以增强代码的安全性和可读性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;

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

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

还可以用到方法中:

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

这样子就会有

365c307f73f2b0b216640d639132ad620d4.jpg

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

提示和上边是一样的

 

  • null_resettable

09c1bd3cf87eefb30566bbd0c3114cd68e9.jpg

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

  • null_unspecified29c8e7391682287ac576d5128ce6fba3d0a.jpg

意思就是 不确定

转载于:https://my.oschina.net/rainwz/blog/2878188

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值