How to implement callback/selector with performSelector in swift? - ios

I am trying to create an equivalent of below method signature (Objective-C) in swift language. I couldn't get an answer on how to get the right equivalent for this. Any help is highly appreciated.
- (void)myMethod:(MyObject*)firstParam
setCallbackObject:(id)obj
withMySelector:(SEL)selector {
[obj performSelector:selector withObject:nil afterDelay:0]
}

First:
NOTE
The performSelector: method and related selector-invoking methods are not imported in Swift because they are inherently unsafe.
If you still want to implement it that way, read below.
You could use NSTimer:
var myTimer: NSTimer = NSTimer.scheduledTimerWithTimeInterval(0.0, target: self, selector: "selectorMethod", userInfo: nil, repeats: false)
String can be used where Selector is needed. It will automatically be converted (autoboxing).
The delay can be of course higher: 0.1 is then equal to 1 tenth of a second.
To call a method like:
func selectorMethod() {
...
}
We need to check before using the selector on the class. But the respondsToSelector: is in the NSObject protocol, so you have to derive at least from that (or one that subclasses from it).
To make it clear, here is the example.
Code:
class Test {
func myMethod(firstParam: String, setCallbackObject obj: AnyObject, withMySelector selector: Selector) {
if obj.respondsToSelector(selector) {
var myTimer: NSTimer = NSTimer.scheduledTimerWithTimeInterval(0.0, target: obj, selector: selector, userInfo: nil, repeats: false)
myTimer.fire()
} else {
println("Warning: does not respond to given selector")
}
}
}
class Test2: NSObject {
func selectorMethod() {
print("worked")
}
}
var test: Test = Test()
var callBackObj: Test2 = Test2()
test.myMethod("thisfirstis", setCallbackObject: callBackObj, withMySelector: Selector("selectorMethod"))
Output:
workedProgram ended with exit code: 0

Related

Swift - Timer not able to access updated instance property

Im my react native project's native module I need to send some data periodically from Objective-C to Swift so I am using NSNotificationCenter. I receive the data successfully in my Swift class, inside the function attached to the observer, and I store it in a property.
If I access this property from any instance method call I can see that the value has updated.
However if I access the same property in the selector function attached to the Timer it appears as if the value has not been updated and I cannot figure out why? It seems as if the timer selector function does not have access to anything except the initial value of the property - I have also tried passing the property as part of userInfo to the Timer but the issue is the same.
[[NSNotificationCenter defaultCenter] postNotificationName:#"stateDidUpdate" object:nil userInfo:state];
class StateController {
var state: Dictionary<String, Any> = Dictionary()
var timer: Timer = Timer()
func subscribeToNotifications() {
NotificationCenter.default.addObserver(
self, selector: #selector(receivedStateUpdate),
name: NSNotification.Name.init(rawValue: "stateDidUpdate"), object: nil)
}
#objc func receivedStateUpdate(notification: NSNotification) {
if let state = notification.userInfo {
self.state = (state as? Dictionary<String, Any>)!
print("\(self.state)") // I can see that self.state has been updated here
}
}
func runTimer() {
self.timer = Timer(timeInterval: 0.1, target: self, selector: #selector(accessState(timer:)), userInfo: nil, repeats: true)
self.timer.fire()
RunLoop.current.add(self.timer, forMode: RunLoop.Mode.default)
RunLoop.current.run(until: Date(timeIntervalSinceNow: 2))
}
#objc func accessState(timer: Timer) {
print("\(self.state)") // state is an empty Dictionary when accessed here
}
func printState() {
"\(self.state)" // value printed is the updated value received from the notification
}
}
I figured out that multiple instances of my Swift class being created was causing the issue. I assumed that React Native would create a singleton when calling a native module but it appears multiple instances are created as I could see how many times the init method was called. Switching to a Singleton pattern resolved the issue for me following this excellent video and this excellent gist on how to create a singleton in a react native project
class StateController {
static let shared = StateController()
private override init() {
}
}

NSTimer scheduledTimerWithTimeInterval - not calling funciton

I want to run a timer in the background. So I created a singleton.
The problem is that after the set 5.0 seconds, it does not call the function timeEnded(). Xcode proposes to add #Objc in front of the function (like this: #Objc func timeEnded() {...) to solve some problem (I don't get what, though). But it still doesn't call that function. Any ideas?
class TimerService {
static let instance = TimerService()
var internalTimer: NSTimer?
func startTimer() {
guard internalTimer != nil else {
return print("timer already started")
}
internalTimer = NSTimer.scheduledTimerWithTimeInterval(5.0, target: self, selector: #selector(TimerService.timeEnded), userInfo: nil, repeats: false)
}
func timeEnded() {
//NSNotificationCenter.defaultCenter().postNotificationName("timerEnded", object: nil)
print("timer Ended")
}
}
You never actually start the timer because your startTimer() function will always return before reaching the line of code where you create the timer.
In your guard statement you only continue the execution of the function if internalTimer != nil but the only place where you set the timer is after that statement. Thus, your timer is never created and internalTimer will always be nil.
This should fix your problem:
func startTimer() {
guard internalTimer == nil else {
return print("timer already started")
}
internalTimer = NSTimer.scheduledTimerWithTimeInterval(5.0, target: self, selector: #selector(TimerService.timeEnded), userInfo: nil, repeats: false)
}
Selectors are a feature of Objective-C and can only be used with methods that are exposed to the dynamic Obj-C runtime. You cannot have a selector to a pure Swift method.
If your class inherits from NSObject then its public methods are exposed to Obj-C automatically. Since your class does not inherit from NSObject you have to use the #objc attribute to indicate that you want this method exposed to Obj-C so that it may be called with an Obj-C selector.
#selector() is the new syntax in Swift 2.2. It allows the compiler to check that the selector you're trying to use actually exists. The old syntax is deprecated and will be removed in Swift 3.0.

Swift selector to protocol function?

I have code like this:
protocol FooP {
...
}
extension FooP {
func doFoo() {
print("foo")
}
func doFoo(timer: NSTimer) {
doFoo()
}
}
class A : NSObject, UITableViewDataSource, FooP {
var timer : NSTimer?
...
func startUpdating() {
timer = NSTimer.scheduledTimerWithTimeInterval(
1.0,
target: self,
selector: Selector("doFoo:"),
userInfo: nil,
repeats: true
)
}
}
Unfortunately it crashes when I start timer the program crashes with
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[xyz.A doFoo:]: unrecognized selector sent to instance 0x7fb2041c4ac0'
How i can make it work (I want to keep implementation of doFoo inside protocol)?
If I move doFoo into A class definition everything works fine, but as i said i want to implement this function inside protocol.
In other words I need selector that says
"Hey I point to function named "doFoo" that is implemented as extension to FooP"
Right now selector seems to say
"Hey I point to function named "doFoo" that is implemented in A class"
Try to play in your playground. Your trouble is, that there is no possibility to define #objc func in protocol extension. So, see possible workaround
import XCPlayground
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
import Foundation
protocol FooP {
}
extension FooP {
func doFoo() {
print("foo")
}
func doFoo(timer: NSTimer) {
print("dofoo")
doFoo()
}
}
class A: FooP {
var timer : NSTimer?
#objc func foo(timer: NSTimer) {
doFoo(timer)
}
func startUpdating() {
timer = NSTimer.scheduledTimerWithTimeInterval(
1.0,
target: self,
selector: "foo:",
userInfo: nil,
repeats: true
)
}
}
let a = A()
a.startUpdating()
Why it works for you if you move doFoo inside class A? That is because your class inherits from NSObject, so #objc keyword is not necessary.
The problem is, NSTimer and the whole Selector() business are Objective-C stuff and do work in Swift domain thanks to bridging. However, Swift's default protocol implementations are not bridged to Objective-C wonderland (yet), and that's why your timer fails. Basically, from Objective-C perspective objects of type A do not respond to a selector doFoo:, period.
So, report this use-case to swift-evolution for the long-term solution. Short-term, use some sort of a workaround.
BTW, you might find it interesting to read (or even participate) in this thread.

Handle the selector parameter in swift

Let's say I declare a function in my CustomTimer class:
class CustomTimer {
class func scheduledTimerWithSelector(aSelector: Selector) -> CustomTimer {
// aSelector ??
}
}
How can I handle this aSelector parameter?
Like the NSTimer.scheduledTimerWithTimeInterval method, how dose it work?
You should check the Selector structure.
From the apple docs:
In Swift, Objective-C selectors are represented by the Selector
structure. You can construct a selector with a string literal, such as
let mySelector: Selector = "tappedButton:". Because string literals
can be automatically converted to selectors, you can pass a string
literal to any method that accepts a selector.
Selector function with Swift :
func selectorFunc(aSel:Selector){
if self.respondsToSelector(aSel){
NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: aSel, userInfo: nil, repeats: false)
}
}
func gooleIt(){
println("Hello")
}
Function Call :
self.selectorFunc(Selector(gooleIt()))
Hope it help you.
You can declare a method with a selector like this and you can call it by creating a UIControl because performSelector methods are not available in Swift:
func methodWithSelector(sel:Selector) {
var control = UIControl()
control.sendAction(sel, to: self, forEvent: nil)
}
If you do not need to call it on the main thread another option is like this:
func methodWithSelector(sel:Selector) {
NSThread.detachNewThreadSelector(sel, toTarget: self, withObject: nil)
}
You will call it like this:
methodWithSelector(Selector("methodCall"))
or like this
methodWithSelector("methodCall")
then you must have a method with the name of the selector
func methodCall() {
println("methodCall")
}

why is performSelector not present in swift

apparently the following is not available in swift anymore:
[self performSelector:#selector(onFlip) withObject:nil afterDelay:0.3];
why is this the case if the following is still present:
NSObject.cancelPreviousPerformRequestsWithTarget(self, selector: singleTapSelector, object: nil)
doesn't nsobject.cancel work with performSelector? why have the cancel functionality but not the perform functionality?
Use
NSTimer.scheduledTimerWithTimeInterval(delay, target: self, selector: "onFlip", userInfo: nil, repeats: false)
instead. No idea why the other one is not available.
We can easily unlock these methods in Swift 1.x! Yay!
These methods from the perfromSelector family actually exist in Swift but they were artificially hidden (by design, I think) prior Swift 2.0. They can be unveiled using swizzling and some Objective-C runtime hacks right in Swift.
Just add this extension file NSObject+PerformSelector.swift and prefix all calls with 🚀 symbol.
In your case the code:
[self performSelector:#selector(onFlip) withObject:nil afterDelay:0.3];
can be rewritten in Swift like this:
self.🚀performSelector("onFlip", withObject: nil, afterDelay: 0.3)
With using this 🚀magical category (class extension):
NSObject+PerformSelector.swift
import Foundation
private var dispatchOnceToken: dispatch_once_t = 0
private var selectors: [Selector] = [
"performSelector:",
"performSelector:withObject:",
"performSelector:withObject:withObject:",
"performSelector:withObject:afterDelay:inModes:",
"performSelector:withObject:afterDelay:",
]
private func swizzle() {
dispatch_once(&dispatchOnceToken) {
for selector: Selector in selectors {
let 🚀selector = Selector("🚀\(selector)")
let method = class_getInstanceMethod(NSObject.self, selector)
class_replaceMethod(
NSObject.self,
🚀selector,
method_getImplementation(method),
method_getTypeEncoding(method)
)
}
}
}
extension NSObject {
func 🚀performSelector(selector: Selector) -> AnyObject? {
swizzle()
return self.🚀performSelector(selector)
}
func 🚀performSelector(selector: Selector, withObject object: AnyObject?) -> AnyObject? {
swizzle()
return self.🚀performSelector(selector, withObject: object)
}
func 🚀performSelector(selector: Selector, withObject object1: AnyObject?, withObject object2: AnyObject?) -> AnyObject? {
swizzle()
return self.🚀performSelector(selector, withObject: object1, withObject: object2)
}
func 🚀performSelector(selector: Selector, withObject object: AnyObject?, afterDelay delay: NSTimeInterval, inModes modes: [AnyObject?]?) {
swizzle()
self.🚀performSelector(selector, withObject: object, afterDelay: delay, inModes: modes)
}
func 🚀performSelector(selector: Selector, withObject object: AnyObject?, afterDelay delay: NSTimeInterval) {
swizzle()
self.🚀performSelector(selector, withObject: object, afterDelay: delay)
}
}
func performFlipOnDelay() {
let delayInSeconds = 1.0
let delay = dispatch_time(DISPATCH_TIME_NOW, Int64(delayInSeconds * Double(NSEC_PER_SEC)))
dispatch_after(delay, dispatch_get_main_queue()) {
onFlip();
}
}
Another round about answer would be the above using GCD to add a delay time for an action to be performed
Taking the answer from Thomas Kilian a step further, primarily to enhance readability on calling clients, I've defined a swift utility, TimerUtil.swift, defining a facade on NSTimer for this particular usecase:
import Foundation
/**
* Convenience function to make a single timer scheduling more readable.
*/
public func invoke( selector:Selector, on target:AnyObject, afterDelay delay:NSTimeInterval ) {
NSTimer.scheduledTimerWithTimeInterval( delay, target: target, selector: selector, userInfo: nil, repeats: false )
}
Then your code can simply call:
invoke( "onFlip", on:self, afterDelay:0.3 )
which more or less resembles performSelector:withObject:afterDelay
In Swift 4
use This to Handle These Types of Warning!
perform(#selector(yourMethodName), with: nil, afterDelay: 0, inModes: [])

Resources