How to identify calling method from a called method in swift - ios

here is a scenario
func callingMethod_A {
self.someCalculation()
}
func callingMethod_B{
self.someCalculation()
}
func someCalculation{
//how to find who called this method? is it callingMethod_A or _B at runtime?
//bla bla
}
how can we get the method name that called it during run time.
thank you.

I worked out a way to do this, for Swift code anyway:
Define a String parameter callingFunction and give it a default value of #function. Do not pass anything from the caller and the compiler provides the calling function name.
Building on #Anu.Krthik's answer:
func someCalculation (parameter: String, callingMethod: String = #function ) {
print("In `\(#function)`, called by `\(callingMethod)`")
}
func foo(string: String) {
someCalculation(parameter: string)
}
foo(string: "bar")
The above prints
In `someCalculation(parameter:callingMethod:)`, called by `foo(string:)`
However, beware that this technique can be subverted if the caller provides a value for the callingFunction parameter. if you call it with:
func foo(string: String) {
someCalculation(parameter: string, callingMethod: "bogusFunctionName()")
}
You get the output
In `someCalculation(parameter:callingMethod:)`, called by `bogusFunctionName()`
instead.

You can use Thread.callStackSymbols like this
func callingMethod_A() {
self.someCalculation()
}
func callingMethod_B(){
self.someCalculation()
}
func someCalculation(){
let origin = Thread.callStackSymbols
print(origin[0])
print(origin[1])
}

Related

Get the name of class & function sent to another class [duplicate]

here is a scenario
func callingMethod_A {
self.someCalculation()
}
func callingMethod_B{
self.someCalculation()
}
func someCalculation{
//how to find who called this method? is it callingMethod_A or _B at runtime?
//bla bla
}
how can we get the method name that called it during run time.
thank you.
I worked out a way to do this, for Swift code anyway:
Define a String parameter callingFunction and give it a default value of #function. Do not pass anything from the caller and the compiler provides the calling function name.
Building on #Anu.Krthik's answer:
func someCalculation (parameter: String, callingMethod: String = #function ) {
print("In `\(#function)`, called by `\(callingMethod)`")
}
func foo(string: String) {
someCalculation(parameter: string)
}
foo(string: "bar")
The above prints
In `someCalculation(parameter:callingMethod:)`, called by `foo(string:)`
However, beware that this technique can be subverted if the caller provides a value for the callingFunction parameter. if you call it with:
func foo(string: String) {
someCalculation(parameter: string, callingMethod: "bogusFunctionName()")
}
You get the output
In `someCalculation(parameter:callingMethod:)`, called by `bogusFunctionName()`
instead.
You can use Thread.callStackSymbols like this
func callingMethod_A() {
self.someCalculation()
}
func callingMethod_B(){
self.someCalculation()
}
func someCalculation(){
let origin = Thread.callStackSymbols
print(origin[0])
print(origin[1])
}

cancelPreviousPerformRequests does not seem to work in Swift 3.0

As the title states, for some reason, the following (simplified) code is not working:
extension InputView: {
func updateTable(text: String) {
NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(loadPlaces(text:)), object: nil)
//NSObject.cancelPreviousPerformRequests(withTarget: self)
self.perform(#selector(loadPlaces(text:)), with: text, afterDelay: 0.5)
prevSearch = inputField.text!;
}
//Private wrapper function
#objc private func loadPlaces(text: String) {
print("loading results for: \(text)")
// locator?.searchTextHasChanged(text: text)
}
}
I call updateTable every time a user edits a UITextField, which calls localPlaces which calls a function that queries google's online places API (commented out). Unfortunately, the print line in loadPlaces is called after every single call to updateTable. From my visual inspection, it seems there is in fact a delay to the print statements, however, the old calls do not cancel. I've tried looking on a lot of StackOverflow threads but I couldn't find anything updated for Swift 3. Am I calling something incorrectly?
PS. If I instead use the commented out, single-argument, cancelPreviousPerformRequests. It works for some reason.
Edit: I have been able to replicate this error in a separate project. So I'm 100% sure that the above code is wrong. If you would like to replicate this error, open up a new iOS project and paste the following code into the default ViewController:
class InputView: UIView {
func updateTable(text: String) {
NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(loadPlaces(text:)), object: nil)
self.perform(#selector(loadPlaces(text:)), with: text, afterDelay: 0.5)
}
//Private wrapper function
#objc private func loadPlaces(text: String) {
print("loading results for: \(text)")
// locator?.searchTextHasChanged(text: text)
}
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let input = InputView()
for i in 0..<200 {
input.updateTable(text: "Call \(i)")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
The explanation in Duncan C's answer is not appropriate for this case.
In the reference of cancelPreviousPerformRequests(withTarget:selector:object:):
Discussion
All perform requests are canceled that have the same target as aTarget, argument as anArgument, and selector as
aSelector.
So, when you have a line like:
<aTarget>.perform(<aSelector>, with: <anArgument>, afterDelay: someDelay)
You can cancel it with:
NSObject.cancelPreviousPerformRequests(withTarget: <aTarget>, selector: <aSelector>, object: <anArgument>)
only when all 3 things aTarget, aSelector and anArgument match.
Please try something like this and check what you see:
class InputView: UIView {
var lastPerformArgument: NSString? = nil
func updateTable(text: String) {
NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(loadPlaces(text:)), object: lastPerformArgument)
lastPerformArgument = text as NSString
self.perform(#selector(loadPlaces(text:)), with: lastPerformArgument, afterDelay: 0.5)
}
//Private wrapper function
#objc private func loadPlaces(text: String) {
print("loading results for: \(text)")
// locator?.searchTextHasChanged(text: text)
}
}
EDIT:
The first part of this answer is wrong. See the edit at the bottom for updated information. I'm leaving the original answer since the discussion might be useful.
It looks to me like there is a bug in the way NSObject maps Swift function names to selectors that is preventing this from working correctly. The only way I was able to get the cancelPreviousPerformRequests function to actually cancel the pending perform() is if the function does not have any parameters. If the function takes a single anonymous parameter or a named parameter then the cancelPreviousPerformRequests function does not cancel the pending perform(_:with:afterDelay:).
Another bug I've found: If you use a function with an anonymous parameter, e.g.:
func foo(_ value: String) {
print("In function \(#function)")
}
Then the result you see in the print statement is:
In function foo
You'll see the same thing if the function has 2, 3, or more anonymous parameters.
If you have a function with no parameters, you get a different result:
func foo() {
print("In function \(#function)")
}
That code will display the message:
In function foo()
(Note the parentheses after the function name.)
EDIT
Note that it seems I was wrong. Apparently the object parameter to cancelPreviousPerformRequests must match what was passed in. You can only pass object:nil to cancelPreviousPerformRequests if the selector was invoked with a nil argument.
To quote the docs:
The argument for requests previously registered with the
perform(:with:afterDelay:) instance method. Argument equality is
determined using isEqual(:), so the value need not be the same object
that was passed originally. Pass nil to match a request for nil that
was originally passed as the argument.

Swift : Create a multi-function multicast delegate

I'm wanting to use a multicast delegate to inform multiple objects when things change. The tutorials I've read that explain this, have a protocol that only has one function that is called directly on the array of delegates. That works fine when there is only one function defined. My Protocol has 6 functions. I want to avoid creating 6 separate functions and reuse a single function that can be applied to my array of delegates.
Quick example: (I understand this is none working, but I just want to get my idea across.
protocol MyProtocol {
func method1()
func method2()
func method3()
}
class TestClass {
var delegates = [MyProtocol]()
func invokeDelegates(delegateMethod: () -> ()) {
for delegate in delegates {
delegate.delegateMethod()
}
}
}
The obvious problem is the compiler complains that "delegateMethod" isn't defined in the original protocol. Is there a way that I cast the method as being part of MyProtocol and the compiler will trust me?
Is this even possible?
Here is a gist of an Multicast Delegate pattern that I use in my projects. It also prevents from having strong reference cycles (memory leaks). WeakWrapper handles this.
Ok. In some of the solutions I see mistakes (strong retain cycles, race conditions, ...)
Here is what I combine based on 1 day research. For the stack of delegates I used NSHashTable, so all the delegates are having weak reference.
class MulticastDelegate <T> {
private let delegates: NSHashTable<AnyObject> = NSHashTable.weakObjects()
func add(delegate: T) {
delegates.add(delegate as AnyObject)
}
func remove(delegate: T) {
for oneDelegate in delegates.allObjects.reversed() {
if oneDelegate === delegate as AnyObject {
delegates.remove(oneDelegate)
}
}
}
func invoke(invocation: (T) -> ()) {
for delegate in delegates.allObjects.reversed() {
invocation(delegate as! T)
}
}
}
func += <T: AnyObject> (left: MulticastDelegate<T>, right: T) {
left.add(delegate: right)
}
func -= <T: AnyObject> (left: MulticastDelegate<T>, right: T) {
left.remove(delegate: right)
}
How to set delegate:
object.delegates.add(delegate: self)
How to execute function on the delegates:
instead of
delegate?.delegateFunction
you use
delegates.invoke(invocation: { $0.delegateFunction })
You need to change the signature of invokeDelegates to take a closure of type (MyProtocol) -> (), and then you need to pass each delegate to the closure.
protocol MyProtocol {
func method1()
func method2()
func method3()
}
class TestClass {
var delegates = [MyProtocol]()
func invokeDelegates(delegateMethod: (MyProtocol) -> ()) {
for delegate in delegates {
delegateMethod(delegate)
}
}
}
The closure should just invoke the appropriate delegate method on its argument. Swift can infer the argument and return types of the closure, and you can use the shorthand $0 to refer to the argument, so the closure can be quite short:
let tester = TestClass()
tester.invokeDelegates(delegateMethod: { $0.method1() })
On the other hand, you could just use Collection.forEach directly on the delegates array (if it's accessible) and skip the invokeDelegates method:
tester.delegates.forEach { $0.method1() }

Swift: Unable to set property value on mutable object paramter

I have the following code:
func enableDelaysContentTouchesIncudlingSubviews(enable: Bool) {
self.setDelaysContentTouches(enable, forObject: self)
for obj: AnyObject in self.subviews {
self.setDelaysContentTouches(enable, forObject: obj)
}
}
private func setDelaysContentTouches(var value: Bool, var forObject obj: AnyObject) {
if obj.respondsToSelector("setDelaysContentTouches:") {
obj.delaysContentTouches = value
}
}
On the second function, the line obj.delaysContentTouches = value raises the following error: Cannot assign to property: 'obj' is immutable
I don't understand the reason since obj is declared as a var parameter. Therefor it should be mutable in my understanding.
Could somebody please explain me the reason and also provide a workaround.
Thanks in advance!
My guess is it's an issue of AnyObject technically being a protocol
Assuming you're working in a view, maybe try something along these lines:
func enableDelaysContentTouchesIncudlingSubviews(enable: Bool) {
self.setDelaysContentTouches(enable, view: self)
self.subviews.forEach({setDelaysContentTouches(enable, view: $0)})
}
private func setDelaysContentTouches(enable: Bool, view: UIView) {
if let viewAsScrollview = view as? UIScrollView {
viewAsScrollview.delaysContentTouches = enable;
}
}
This is a much swiftier way of doing things, more clear, and doesn't use "respondsToSelector"
More info, and possibly a more direct answer about respondsToSelector in swift here

Gameplaykit GKState, swift func with two parameters

I'm sure that is a simple question for you.
How can I write a func with two parameters with one GKState?
UPDATE
Apple use
func willExitWithNextState(_ nextState: GKState)
If I use somefunc(state:GKState) works fine
while somefunc(state:GKState, string:String) does't work, why???
Other example
I've tried this:
class Pippo:GKState {}
//1
func printState (state: GKState?) {
print(state)
}
printState(Pippo) //Error cannot convert value of type '(Pippo).Type' (aka 'Pippo.Type') to expected argument type 'GKState?'
//2
func printStateAny (state: AnyClass?) {
print(state)
}
printStateAny(Pippo) //NO Error
//3
func printStateGeneral <T>(state: T?) {
print(state)
}
printStateGeneral(Pippo) //No Error
//4
func printStateAnyAndString (state: AnyClass?, string:String) {
print(state)
print(string)
}
printStateAnyAndString(Pippo/*ExpectedName Or costructor*/, string: "Hello") //ERROR
printStateAnyAndString(Pippo()/*ExpectedName Or costructor*/, string: "Hello") //ERROR cannot convert value of type 'Pippo' to expected argument type 'AnyClass?'
SOLUTION THANKS #0x141E
func printStateAnyAndString (state: GKState.Type, string:String) {
switch state {
case is Pippo.Type:
print("pippo")
default:
print(string)
}
}
printStateAnyAndString(Pippo.self, string: "Not Pippo")
Thanks for reply
If you want a parameter to be a class, use Class.Type or AnyClass
func printState (state: AnyClass, string:String) {
print(state)
print(string)
}
and use Class.self as the argument
printState(Pippo.self, string:"hello pippo")
Update
If your function definition is
func printState (state:GKState, string:String) {
if state.isValidNextState(state.dynamicType) {
print("\(state.dynamicType) is valid")
}
print(state)
print(string)
}
you'll need to pass in an instance of GKState (or a subclass of GKState) as the first argument, not the class/subclass itself. For example,
let pippo = Pippo()
printState (pippo, "Hello")
Throughout your sample code you have used AnyClass, whereas you should (probably) be using AnyObject. AnyClass refers to a class definition, whereas AnyObject is an instance of a class.
class MyClass { }
func myFunc1(class: AnyClass)
func myFunc2(object: AnyObject)
let myObject = MyClass() // create instance of class
myFunc1(MyClass) // myFunc1 is called with a class
myFunc2(myObject) // myFunc2 is called with an instance
You have also made most of your parameters Optionals with the "?", whereas it doesn't look required. For example:
printState(nil) // What should this do?

Resources