iOS9 相关
iOS9新出关键字 nonnull
,nullable
,null_resettable
,_Null_unspecified
只能修饰对象,不能修饰基本数据类型.
iOS9新出的关键字:用来修饰属性,或者方法的参数,方法的返回值 好处: 1.迎合swift,因为swift 是强类型的 2.提高我们开发人员开发规范,减少程序员之间交流
-
1、
nullable
作用:表示可以为空 书写规范:复制代码
// 方式一: @property (nonatomic, strong, nullable) NSString *name; // 方式二: @property (nonatomic, strong) NSString *_Nullable name; // 方式三: @property (nonatomic, strong) NSString *__nullable name;
- 2、`nonnull`
non:非 null:空
书写格式:
```
// 方式一
@property (nonatomic, strong, nonnull) NSString *icon;
// 方式二
@property (nonatomic, strong) NSString * _Nonnull icon;
// 方式三
@property (nonatomic, strong) NSString * __nonnull icon;
//方式四
在NS_ASSUME_NONNULL_BEGIN和NS_ASSUME_NONNULL_END之间,定义的所有对象属性和方法默认都是nonnull
```
方法中,关键字书写规范
```
- (nonnull NSString *)test:(nonnull NSString *)str;
- (NSString * _Nonnull)test1:(NSString * _Nonnull)str;
```
- 3、`null_resettable`
get:不能返回为空, set可以为空 例如:Controller中的view必须不能为空的
复制代码
- (UIView *)view { if(_view == nil) { [self loadView]; [self viewDidLoad]; } return _view; }
如果使用null_resettable声明的属性,必须保证setter or getter 是有值的
复制代码
-
(void)setName:(NSString *)name { if (name == nil) { name = @"123"; } _name = name; }
-
(NSString *)name { if (_name == nil) { _name = @"123"; } return _name; }
复制代码
null_resettable: get:不能返回为空, set可以为空 // 注意;如果使用null_resettable,必须 重写get方法或者set方法,处理传递的值为空的情况 // 书写方式: @property (nonatomic, strong, null_resettable) NSString *name;
_Null_unspecified:不确定是否为空 例如:不知道是使用set or get方法 如 self.name 书写方式只有这种 // 方式一 @property (nonatomic, strong) NSString *_Null_unspecified name; // 方式二 @property (nonatomic, strong) NSString *__null_unspecified name;
- 4、泛型
>
作用:限制类型
>
泛型使用场景:
1.在集合(数组,字典,NSSet)中使用泛型比较常见.
2.当声明一个类,类里面的某些属性的类型不确定,这时候我们才使用泛型.
>
泛型书写规范
在类型后面定义泛型,NSMutableArray<UITouch *> *datas
>
泛型修饰:
只能修饰方法的调用.
>
泛型好处:
1.提高开发规范,减少程序员之间交流
2.通过集合取出来对象,直接当做泛型对象使用,可以直接使用点语法
#
```
__covariant(协变):用于泛型数据强转类型,可以向上强转,子类 可以转成 父类
__contravariant(逆变):用于泛型数据强转类型,可以向下强转, 父类 可以 转成子类
```
常见场景:
场景一:
复制代码
@property (nonatomic, strong) NSMutableArray<NSString *> *datas; ``` datas 表示里面的元素都是字符串类型,这样取出来的元素就可以调用对象本身的方法,如果不用泛型,则数组中的元素是id类型的,还需要转成字符串才可以调用自身的方法。
场景二:
- 5、
__kindof
作用: 表示当前类或者它子类 __kindof :在调用的时候,很清楚的知道返回类型
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath;
复制代码