顯示具有 develop 標籤的文章。 顯示所有文章
顯示具有 develop 標籤的文章。 顯示所有文章

2013年12月10日 星期二

iOS 開發筆記 - 透過 semaphore 讓 function 特性從 nonblocking 回到 blocking 模式

相信從事 Window Programming 的大多都知道 Main thread(UI thread) 的特性,例如 Main Thread 用來處理事件,須儘量避免做太久的工作,此外,所謂的 nonblocking 的原理就只是在建立一支 thread 去執行任務,任務完成後在依照設計返回到 Main thread 去更動 UI 狀況。
因此,採用一些手機視窗程式等第三方 SDK 時,更是容易碰到 nonblocking functions。這會使得規劃的 function flow 有點亂掉。

在 iOS app development 環境中,以 block 為例,可以透過 semaphore 來達成 blocking 效果,如:

dispatch_semaphore_t waitJobDone = dispatch_semaphore_create(0);
[self callBlock:^{
// do something
dispatch_semaphore_signal(waitJobDone);
}];
dispatch_semaphore_wait(waitJobDone, DISPATCH_TIME_FOREVER);


順便筆記一下其他東西,隨意使用 nonblocking 用法:

dispatch_async( dispatch_queue_create(“job_running”, NULL), ^{


});


在非 UI thread 中,又想動 UI 方式:

dispatch_async( dispatch_queue_create("job_running", NULL), ^{
// do something ...
     
dispatch_async(dispatch_get_main_queue(), ^{
// update ui
});
});


最後一提,如果用到的 SDK 跟網路相關的(NSURLConnection),那大多不能用 semaphore 來使之改成 blocking 模式(或是改法很繁雜要深入or破壞SDK架構),這跟 NSURLConnection Delegate Callback 設計有關(NSRunLoop)。

iOS 開發筆記 - ARC forbids explicit message send of 'dealloc'

最近我也投入 ARC 開發模式 XD 再也不去管到底要不要對哪個 object 執行 release 的議題,這適應其實也不難,就真的不要寫 [object release] 即可 XD

但有些時候還是要在物件銷毀時去做一些處理,例如解決或等待相關的事件完成,就常常會寫這段:

- (void)dealloc
{
    // do something ...
    [super dealloc];

}


結果,Xcode 就噴這段訊息:

ARC forbids explicit message send of 'dealloc'

Transitioning to ARC Release Notes 文件查證:
You may implement a dealloc method if you need to manage resources other than releasing instance variables. You do not have to (indeed you cannot) release instance variables, but you may need to invoke [systemClassInstance setDelegate:nil] on system classes and other code that isn’t compiled using ARC. 
Custom dealloc methods in ARC do not require a call to [super dealloc] (it actually results in a compiler error). The chaining to super is automated and enforced by the compiler.

僅需改成這樣了:

- (void)dealloc
{
    // do something ...
}