Last active
October 10, 2021 06:45
-
-
Save pablogm/d20120a97912fea44bed to your computer and use it in GitHub Desktop.
Swift extension to add some methods to the NSThread class to run a block on any thread you have a reference to.
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
// | |
// NSThread+blocks.swift | |
// Swift extensions | |
// | |
import Foundation | |
public typealias Block = @convention(block) () -> Void | |
extension NSThread { | |
/** | |
Perform block on current thread | |
- parameter block: block to be executed | |
- parameter wait: | |
*/ | |
func performBlock(block: Block, waitUntilDone wait: Bool) { | |
NSThread.performSelector("runBlock:", onThread: self, withObject: block as? AnyObject, waitUntilDone: wait) | |
} | |
/** | |
Perform block on main thread | |
- parameter block: block to be executed | |
*/ | |
class func performBlockOnMainThread(block: Block) { | |
NSThread.mainThread().performBlock(block) | |
} | |
/** | |
Perform block in background thread | |
- parameter block: block to be executed | |
*/ | |
class func performBlockInBackground(block: Block) { | |
NSThread.performSelectorInBackground("runBlock:", withObject: block as? AnyObject) | |
} | |
/** | |
Execute block | |
- parameter block: block to be executed | |
*/ | |
class func runBlock(block: Block) { | |
block() | |
} | |
/** | |
Perform block on current thread | |
- parameter block: block to be executed | |
*/ | |
func performBlock(block: Block) { | |
if NSThread.currentThread().isEqual(self) { | |
block() | |
} | |
else { | |
self.performBlock(block, waitUntilDone: false) | |
} | |
} | |
/** | |
Perform block | |
- parameter block: block to be executed | |
- parameter delay: | |
*/ | |
func performBlock(block: Block, afterDelay delay: NSTimeInterval) { | |
self.performSelector("performBlock:", withObject: block as? AnyObject, afterDelay: delay) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Where would I put the extension?