一句話介紹:最知名的 Objective-C 開源網路庫。
GitHub:傳送門
說明:本拾遺系列只專注於程式碼與工程層面的知識點,架構層面的探討作者原文已有詳細論述。
OC 中的 @import 以及 Swift 中的 import,其實都建立在 modulemap 機制之上。
@import 的用法可參考:@import vs #import__unused——避免「變數宣告後未使用」造成編譯警告。__autoreleasing)可參考:iOS 開發 ARC 記憶體管理技術要點。NS_DESIGNATED_INITIALIZER——宣告 designated 初始化方法後,其餘初始化方法若未呼叫 designated 初始化便會出現警告,可參考:Xcode 6 Objective-C Modernization。DEPRECATED_ATTRIBUTE(標記過期)、NS_SWIFT_NOTHROW(便於 OC 遷移至 Swift)等。FOUNDATION_EXPORT——對 extern 的相容性封裝,依不同平台轉譯為對應的 extern 形式。NS_ASSUME_NONNULL_BEGIN / NS_ASSUME_NONNULL_END——在此範圍內的變數、參數與返回值預設標記為 nonnull。這段程式常被單獨摘出來放進各家專案,值得細讀其思路:
/**
Returns a percent-escaped string following RFC 3986 for a query string key or value.
RFC 3986 states that the following characters are "reserved" characters.
- General Delimiters: ":", "#", "[", "]", "@", "?", "/"
- Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "="
In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow
query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/"
should be percent-escaped in the query string.
*/
NSString * AFPercentEscapedStringFromString(NSString *string) {
static NSString * const kAFCharactersGeneralDelimitersToEncode = @":#[]@"; // 不含 "?" 與 "/"
static NSString * const kAFCharactersSubDelimitersToEncode = @"!$&'()*+,;=";
NSMutableCharacterSet * allowedCharacterSet = [[NSCharacterSet URLQueryAllowedCharacterSet] mutableCopy];
[allowedCharacterSet removeCharactersInString:
[kAFCharactersGeneralDelimitersToEncode stringByAppendingString:kAFCharactersSubDelimitersToEncode]];
// 以下為針對非單-byte 字元的分批處理
static NSUInteger const batchSize = 50;
NSUInteger index = 0;
NSMutableString *escaped = @"".mutableCopy;
while (index < string.length) {
NSUInteger length = MIN(string.length - index, batchSize);
NSRange range = NSMakeRange(index, length);
// 避免把像 emoji 這樣的 compose 字元序列切斷
range = [string rangeOfComposedCharacterSequencesForRange:range];
NSString *substring = [string substringWithRange:range];
NSString *encoded = [substring stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacterSet];
[escaped appendString:encoded];
index += range.length;
}
return escaped;
}
這段程式有兩個值得學習的細節:一是嚴格依 RFC 3986 界定哪些字元該被編碼(刻意保留「?」與「/」);二是分批(每批 50 個字元)處理並以 rangeOfComposedCharacterSequencesForRange: 校正邊界,避免把一個完整的字元序列(例如 emoji)切成兩半而產生亂碼。這正是「邊界條件」在字串處理中的典型體現。
