iosiOS知识点详解将来跳槽用

OC中的一些修饰关键字

2016-07-08  本文已影响1265人  jianshu_wl
@property (nullable, nonatomic, strong) NSString *name;
@property (nonatomic, strong) NSString * _Nullable name;
@property (nonatomic, strong) NSString * __nullable name;
@property (nonnull, nonatomic, strong) NSString *name;
@property (nonatomic, strong) NSString * _Nonnull name;
@property (nonatomic, strong) NSString * __nonnull name;

可以通过泛型的特性来限制数组中的元素只能为某一种类型, 例如有一个数组,我们想让放入里面的元素都为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所需的类型,如下图:

自定义泛型 强转时报错

如果想要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

例如在UITableView类中有如下方法:

- (nullable __kindof UITableViewCell *)cellForRowAtIndexPath:(NSIndexPath *)indexPath; 

这里的__kindof表示的含义就是该方法返回的是UITableViewCell对象,或者是UITableViewCell的子类对象.

上一篇下一篇

猜你喜欢

热点阅读