How to call private class function from selector in Swift.?

1. You can write your function as follow :

@objc private class func startAnimation() {}

or

dynamic private class func startAnimation() {}  // not recommended

When you declare a swift function as dynamic, you made it seems like a Objective-C function (Objective-C follows Dynamic Dispatch), or we can say, the function is a Dynamic Dispatch Function right now, which can be called in Selector.

But in this case, we just need to let this function has a Dynamic Feature, so declare it as @objc is enough.

2. If you write your function as

@objc private func xxxxx(){}

the target in NSTimer should be self, but if you write your function as

@objc private class func xxxx(){} // Assuming your class name is 'MyClass'

the target in NSTimer should be MyClass.self.


If you're fine with changing the class function to be an instance function you could use this:

performSelector(Selector(extendedGraphemeClusterLiteral: "aVeryPrivateFunction"))

Note: be sure to mark your private function with @objc like this:

@objc private func aVeryPrivateFunction(){
    print("I was just accessed from outside")
}

read more here


You can't call private methods with selectors. That is the whole point of making the methods private, so they are not accessible from the outside.

You are also sending an instance of self as target to class method which is why it will not work. You need to either send a class or remove class from method.

Tags:

Ios

Swift