Enumeration Macros
NS_ENUM和NS_OPTIONS宏提供一個簡潔、簡單的定義枚舉的方法和基于c語言的選項。這些宏在Xcode中實現(xiàn)可以顯式地指定枚舉類型和選項的大小。此外,這種由舊的編譯器語法聲明枚舉的方式,可以被新的編譯器正確評估和解釋潛在的類型信息。
使用NS_ENUM宏定義枚舉,互斥的一組值:
typedef NS_ENUM(NSInteger, UITableViewCellStyle){
UITableViewCellStyleDefault,
UITableViewCellStyleValue1,
UITableViewCellStyleValue2,
UITableViewCellStyleSubtitle
}
NS_ENUM宏幫助定義枚舉的名稱和類型,在本例中名稱為UITableViewCellStyle類型為NSInteger。枚舉類型應該是NSInteger。
使用NS_OPTIONS宏來定義選項,一組位掩碼值,可以組合在一起:
typedef NS_OPTIONS(NSUInteger, UIViewAutoresizeing){
UIViewAutoresizeingNone = 0,
UIViewAutoresizeingFlexibleLeftMargin = 1 << 0,
UIViewAutoresizeingFlexibleWidth = 1 << 1,
UIViewAutoresizeingFlexibleRightMargin = 1 << 2,
UIViewAutoresizeingFlexibleTopMargin = 1 << 3,
UIViewAutoresizeingFlexibleHeight = 1 << 4,
UIViewAutoresizeingFlexibleBottomMargin = 1 << 5
}
像這樣的枚舉,NS_OPTIONS宏定義一個名稱和一個類型。然而,通常類型應該是NSUInteger。
怎樣適配
代替你的枚舉聲明,如:
enum{
UITableViewCellStyleDefault,
UITableViewCellStyleValue1,
UITableViewCellStyleValue2,
UITableViewCellStyleSubtitle
};
typedef NSInteger UITableViewCellStyle;
用NS_ENUM語法:
typedef NS_ENUM(NSInteger, UITableViewCellStyle){
UITableViewCellStyleDefault,
UITableViewCellStyleValue1,
UITableViewCellStyleValue2,
UITableViewCellStyleSubtitle
}
但是,當你使用enum去定義一個位掩碼,像這樣:
enum {
UIViewAutoresizeingNone = 0,
UIViewAutoresizeingFlexibleLeftMargin = 1 << 0,
UIViewAutoresizeingFlexibleWidth = 1 << 1,
UIViewAutoresizeingFlexibleRightMargin = 1 << 2,
UIViewAutoresizeingFlexibleTopMargin = 1 << 3,
UIViewAutoresizeingFlexibleHeight = 1 << 4,
UIViewAutoresizeingFlexibleBottomMargin = 1 << 5
};
typedef NSUInteger UIViewAutoresizing;
用NS_OPTIONS宏:
typedef NS_OPTIONS(NSUInteger, UIViewAutoresizeing){
UIViewAutoresizeingNone = 0,
UIViewAutoresizeingFlexibleLeftMargin = 1 << 0,
UIViewAutoresizeingFlexibleWidth = 1 << 1,
UIViewAutoresizeingFlexibleRightMargin = 1 << 2,
UIViewAutoresizeingFlexibleTopMargin = 1 << 3,
UIViewAutoresizeingFlexibleHeight = 1 << 4,
UIViewAutoresizeingFlexibleBottomMargin = 1 << 5
}
或者,您可以在Xcode使用現(xiàn)代objective-c變換器自動進行轉換您的代碼。更多信息請看使用Xcode重構你的代碼。
Automatic Reference Counting (ARC)
自動引用計數(shù)(ARC)是一個編譯器特性,它提供了Objective-C對象的自動內存管理。代替你不必記得使用retain,release和autorelease。ARC評估對象的生命周期需求并自動插入適當?shù)膬却婀芾硪笤诰幾g時間。編譯器也會為你產生適當?shù)膁ealloc方法。
怎樣適配
Xcode提供了一個工具,自動化轉換的(如刪除retain和release調用)幫助你解決不能自動修復的問題。使用ARC工具:選擇Edit > Refactor > Convert to Objective-C ARC。這個工具轉換項目中所有的文件使用ARC。
更多的信息,看Transitioning to ARC Release Notes.
Refactoring Your Code Using Xcode
Xcode提供了一個現(xiàn)代objective - c變換器,在轉向現(xiàn)代化過程中可以幫助你。雖然轉換器有助于識別和潛在應用現(xiàn)代化的機制,但它沒有解釋代碼的語義。例如,它不會發(fā)現(xiàn)-toggle方法是一種動作,影響你的對象的狀態(tài),并將錯誤地提供現(xiàn)代化這一行動是一個屬性。確保手動審查和確認任何轉換器提供的使您的代碼的更改。
前面描述的現(xiàn)代化,轉換器提供了:
- 改變id到instancetype在合適的地方
- 改變enum到NS_ENUM或NS_OPTIONS
- 更新到@property語法
除了這些現(xiàn)代化,這個轉換器推薦額外的代碼變更,包括:
- 轉換到字面意思,像[NSNumber numberWithInt:3]變成@3.
- 用下標,像[dictionary setObject:@3 forKey:key]變成dictionary[key] = @3.
使用modern Objective-C converter,Edit > Refactor > Convert to Modern Objective-C Syntax.