這是一篇學習總結筆記,內容橫跨繪圖、多執行緒、網路監測以及同步/非同步請求等主題,適合初學者作為複習參考。
透過 drawRect 取得繪圖上下文,將三個觸控點連成一條閉合線條:
-(void)drawRect:(CGRect)rect
{
CGContextRef context = UIGraphicsGetCurrentContext();
CGPoint addLines[] = { firstPoint, secondPoint, thirdPoint, firstPoint };
CGContextAddLines(context, addLines, sizeof(addLines)/sizeof(addLines[0]));
CGContextStrokePath(context);
}
在 touchesEnded 方法中收集觸控點,只保留最後三個,並呼叫 setNeedsDisplay 觸發重繪:
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint point = [touch locationInView:self];
[pointArray addObject:[NSValue valueWithCGPoint:point]];
if (pointArray.count > 3) { [pointArray removeObjectAtIndex:0]; }
if (pointArray.count == 3) {
firstPoint = [[pointArray objectAtIndex:0] CGPointValue];
secondPoint = [[pointArray objectAtIndex:1] CGPointValue];
thirdPoint = [[pointArray objectAtIndex:2] CGPointValue];
}
[self setNeedsDisplay];
}
iOS 提供三種多執行緒方案,抽象層級由低到高、使用難度也逐步降低:
1. NSThread:最輕量級,但需要自行管理執行緒生命週期與同步,加鎖會帶來系統開銷。
2. Cocoa NSOperation:不需操心執行緒管理,主要相關類別為 NSOperation 與 NSOperationQueue,可透過 NSInvocationOperation、NSBlockOperation 或自訂子類實作。
3. GCD(Grand Central Dispatch):Apple 提供的高效多核解決方案,也是官方最推薦的方式。
NSThread 有兩種建立方式:initWithTarget:selector:object: 為實例方法,會先建立再執行;detachNewThreadSelector:toTarget:withObject: 為類方法,會直接建立並啟動執行緒。selector 只能有一個參數且無回傳值。
關於執行緒鎖,可使用 NSLock(lock/unlock)或 NSCondition 來保證資料的正確性。
使用 NSOperationQueue 時,可透過 setMaxConcurrentOperationCount: 控制並發數量,預設值為 -1,代表不限制,會同時執行佇列中的所有操作。
利用 Reachability 類別,將通知觀察者加入訊息中心,即可全域監測網路狀態:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachablityChanged:) name:kReachabilityChangedNotification object:nil];
self.hostReach = [[Reachability reachabilityWithHostName:@"www.baidu.com"] retain];
[self.hostReach startNotifier];
在回呼方法中,根據 currentReachabilityStatus 判斷是無網路、WiFi 還是行動網路,並給出對應提示。
同步請求有時會阻斷主執行緒,非同步請求一般不會,因此實務上多採用非同步方式。非同步請求透過 delegate 回呼完成資料接收,共有四個關鍵回呼方法:didReceiveResponse(開始回應)、didReceiveData(開始接收資料)、connectionDidFinishLoading(接收完成)、didFailWithError(接收失敗)。
兩者的主要區別在於:
1. GET 將參數直接附加在 URL 後方;POST 則將參數放進 body。
2. POST 需使用 NSMutableURLRequest。
3. POST 透過 setHTTPBody: 設定參數主體。
4. POST 必須手動透過 setHTTPMethod:@"POST" 聲明請求方式。
以上就是一個 QQ 在線狀態查詢工具的核心程式碼,涵蓋了非同步請求、GET 與 POST 兩種提交方式。