-
nullable: 表示对象可以为空
下面是三种写法:
@property (nullable, nonatomic, strong) NSString *name;
@property (nonatomic, strong) NSString * _Nullable name;
@property (nonatomic, strong) NSString * __nullable name;
-
nonnull: 表示对象不能为空
下面是三种写法:
@property (nonnull, nonatomic, strong) NSString *name;
@property (nonatomic, strong) NSString * _Nonnull name;
@property (nonatomic, strong) NSString * __nonnull name;
-
null_resettable: 当用此关键字修饰对象属性时, 表示通过getter方法获取的对象属性不为空,通过setter方法进行赋值时可以为空, 而且必须实现其getter或者setter方法, 不然会报警告. -
泛型
可以通过泛型的特性来限制数组中的元素只能为某一种类型, 例如有一个数组,我们想让放入里面的元素都为NSString类型, 那么可以这么写:
@property (nonatomic, strong) NSMutableArray<NSString *> * names;
我们也可以自定义泛型:
下面我们新建一个Animal类, 并给Animal类添加一个表示物种的属性species, 这个属性的类型时是不确定的.
Animal.h中代码如下:
#import <Foundation/Foundation.h>
@interface Animal<ObjectType> : NSObject
@property (nonatomic, strong) ObjectType species;
@end
接着在ViewController.m进行测试,在初始化时如果指定了ObjectType为某一类型后, 在对属性species进行赋值时, xcode会进行提示species所需的类型,如下图:
自定义泛型
-
__covariant: 协变, 子类可以强转为父类(里氏替换原则).
__contravariant: 逆变, 父类可以强转为子类.
新建两个Animal对象a和b,分别制定属性的类型为NSString和NSMutableString类型,通过a和b进行强转时会出现如下警告:
强转时报错
如果想要a = b不报警,也就是允许子类强转为父类,则需要在Animal.h加入__covariant关键字, 代码如下:
#import <Foundation/Foundation.h>
@interface Animal<__covariant ObjectType> : NSObject
@property (nonatomic, strong) ObjectType species;
@end
如果想要b = a不报警,也就是允许父类强转为子类,则需要在Animal.h加入__contravariant关键字, 代码如下:
#import <Foundation/Foundation.h>
@interface Animal<__contravariant ObjectType> : NSObject
@property (nonatomic, strong) ObjectType species;
@end
-
__kindof: 表示当前类或者其子类.
例如在UITableView类中有如下方法:
- (nullable __kindof UITableViewCell *)cellForRowAtIndexPath:(NSIndexPath *)indexPath;
这里的__kindof表示的含义就是该方法返回的是UITableViewCell对象,或者是UITableViewCell的子类对象.













网友评论