在iOS9.0 之后添加了一些新的關鍵字, 在這里復習一下闻丑, 順便做個總結(jié)枫弟, 以便于讓自己的代碼更加規(guī)范。
常用關鍵字:
1. nonnull \ __nonnull :這個屬性 代表setter 和 getter 都不能為nil
使用方法:
@property (nonatomic, strong, nonnull) NSArray *names;
@property (nonatomic, strong) NSArray * __nonnull names;
2. nullable \ __nullable :這個屬性代表 setter 和 getter 都可以為nil
使用方法:
@property (nonatomic, strong, nullable) NSArray *names;
@property (nonatomic, strong) NSArray * __nullable names;
溫馨提示:
默認情況下 屬性不加nullable, setter 和 getter 也都是可以為nil始衅,加上nullable 更多的作用在于程序員之間的溝通交流(提醒同事某個屬性可能是nil)
3.null_resettable : setter可以為nil, getter不可以為nil
@property (null_resettable, nonatomic, strong) NSArray *names;
4.NS_ASSUME_NONNULL_BEGIN和NS_ASSUME_NONNULL_END之間的所有屬性默認都是nonnull
泛型:
1. 常用的泛型 標明數(shù)組中裝的東西, 便于使用
@property (nonatomic, strong) NSMutableArray<NSString *> *names;
@property (nonatomic, strong) NSMutableDictionary<NSString *, NSNumber *> *books;
2.自定義泛型
Bag<Book *> *bag1 = [[Bag alloc] init];
[bag1 get:0];
Bag<Car *> *bag2 = [[Bag alloc] init];
[bag2 get:0];
另外一個類寫法:
@interface Bag<__contravariant ObjectType> : NSObject
- (void)add:(ObjectType)object;
- (ObjectType)get:(int)index;
@end
3.
__covariant : 小類型(泛型類的子類類型) -> 大類型(泛型類的父類類型) 時缭保, 不會報??
__contravariant : 大類型(泛型類的父類類型) -> 小類型(泛型類的子類類型)時汛闸, 不會報??
__kindof
1. 一個方法中 返回參數(shù)中修飾符添加 __kindof
目的是:告訴編譯器返回值可能是一個類(NSString),也可能是這個類的子類(NSMutableString)這樣在調(diào)用時, 不用進行強制轉(zhuǎn)換