Created
August 12, 2014 15:42
-
-
Save sergiomtzlosa/c10721eeab3ca2dd46d7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// SMSync.swift | |
// TableExample | |
// | |
// Created by sid on 11/08/14. | |
// Copyright (c) 2014 Sergio Martinez-Losa. All rights reserved. | |
// | |
import Foundation | |
/** | |
A semaphotre class that waits till async executions ends | |
example: | |
var request : HTTPRequest = HTTPRequest() | |
var callback2 : (() -> ()) = { () -> () in | |
// something for callback | |
SMSync.endSync() | |
} | |
SMSync.beginSync({() -> () in | |
request.method(callback); | |
}) | |
*/ | |
typealias Completion = (() -> ()) | |
var semaphone : dispatch_semaphore_t! | |
class SMSync : NSObject | |
{ | |
class func beginSync(completion : Completion) | |
{ | |
semaphone = dispatch_semaphore_create(0) | |
completion(); | |
while (dispatch_semaphore_wait(semaphone, DISPATCH_TIME_NOW) != 0) | |
{ | |
NSRunLoop.currentRunLoop().runUntilDate(NSDate(timeIntervalSinceNow:0)) | |
} | |
} | |
class func endSync() | |
{ | |
SMSync.performSync(semaphone) | |
} | |
class func performInMainThreads(completion : Completion) | |
{ | |
dispatch_async(dispatch_get_main_queue()) { | |
completion(); | |
} | |
} | |
private class func performSync(sem : dispatch_semaphore_t) | |
{ | |
dispatch_semaphore_signal(sem); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment