Objective-C中的關鍵字

一、Nullability檢測的支持

1. 簡介

在以前的OC中,開發中經常會遇到 因爲某個方法應該返回實例對象而實際返回了空導致應用崩潰,而 Nullability 的用處就在這,它可以提示開發者做是否爲空的判斷的提示。在 iOS 9 中,提出了新的關鍵字 :nullable、nonnull、null_resettable、_Null_unspecified;
注意 : 上述的關鍵字只能修飾 OC 對象,不能修飾 基本數據類型

2. nullable

作用 : 可以爲空
寫法 : 

// 寫法 1

@property (nonatomic, strong, nullable) NSString * name_1;

// 寫法 2

@property (nonatomic, strong) NSString * __nullable name_2;

// 寫法 3

@property (nonatomic, strong) NSString * _Nullable name_3;


3. nonnull

作用 : 不能爲空
寫法 :

// 寫法 1

@property (nonatomic, strong, nonnull) NSString * name_1;

// 寫法 2

@property (nonatomic, strong) NSString * __nonnull name_2;

// 寫法 3

@property (nonatomic, strong) NSString * _Nonnull name_3;

注意 : 在 NS_ASSUME_NONNULL_BEGIN 和 NS_ASSUME_NONNULL_END 之間,定義的所有對象和方法默認爲 nonnull


4. null_resettable

作用 : getter 方法不能返回空;setter 方法可以
寫法 :

@property (nonatomic, strong, null_resettable) NSString * name_1;

注意 : 如果使用 null_resettable ,則必須重寫 getter或setter 方法

5. null_unspecified

作用 : 不確定是否爲空
寫法 :

// 寫法 1

@property (nonatomic, strong) NSString * __null_unspecified name_1;

// 寫法 2

@property (nonatomic, strong) NSString * _Null_unspecified name_2;


二、類型通配符

1.在程序中經常會見到 ObjectType,它既不是類型,也不是關鍵字,只是一個類型通配符

三、__kindof

作用 : 表示當前類或者它的子類
書寫 :

__kindof classname *




發佈了31 篇原創文章 · 獲贊 0 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章