Swift: determine what object called a function?

前端 未结 4 1703
感情败类
感情败类 2020-12-09 01:33

I am writing some Swift code and I would like to know the class of the object that called the function. I don\'t want to pass in any parameters. From within the function I w

相关标签:
4条回答
  • 2020-12-09 02:12

    If you want to do that using swift, you can do this:

    func debug(file: String = #file, line: Int = #line, function: String = #function) -> String {
        return "\(file):\(line) : \(function)"
    }
    

    It's quite simple. Ignore syntax highlight, it's wrong.

    0 讨论(0)
  • 2020-12-09 02:23

    To access the underlying class of a method from within itself, use the dynamicType property:

     self.dynamicType
    

    If you want to know the origin of the original call, you can use NSThread to return debugging information about the stack:

     NSThread.callStackSymbols()
    

    This method returns a descriptive array of values that you're used to seeing when exceptions are thrown. The strings represent a backtrace of all current activity on your call stack.

    I don't want to be presumptuous, but it seems to me that outside of debugging, there isn't a good reason, conceptually, at least, to know the origin of a specific method call for any and every function. If you need to retrieve the class Type of the last method call on the stack, why not implement an interface that lets you access this information through a straightforward route?

    0 讨论(0)
  • 2020-12-09 02:28

    You can use following template to know from which file, line number in file, and function this someFunction is called:

    func someFunction(file: String = #file, line: Int = #line, function: String = #function)
    {
        NSLog("\(file.lastPathComponent):\(line) : \(function)")
    }
    
    0 讨论(0)
  • 2020-12-09 02:35

    Swift:

    Add a (sender: Anyobject) as parameter to that function, and then print the sender (the function caller) like this:

    func yourFunc(sender: AnyObject){
         print(sender)
    }
    

    Or add a symbolic breakpoint with a po thread to see the stack trace of the caller of the method

    0 讨论(0)
提交回复
热议问题