Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ios

swift

Currently i'm doing like this,

Calling selector as:

NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: "startAnimation:", userInfo: loadingView, repeats: true)

Selector method is as:

private class func startAnimation(timer:NSTimer){
    var loadingCircularView = timer.userInfo as UIView
}

I'm getting warning, and app crashes:

warning: object 0x67c98 of class ‘ClassName’ does not implement methodSignatureForSelector: -- trouble ahead Unrecognized selector +[ClassName startAnimation:]
like image 732
Mohammad Zaid Pathan Avatar asked May 04 '15 09:05

Mohammad Zaid Pathan


People also ask

How do I call a private method in Swift?

You have to find the private headers, copy them to your project, create a bridging header file, and import the private headers. Or you can use message sending techniques to perform a method selector on a target object, and extract the returned value and convert it to a Swift type.

What is a private function in Swift?

Private access restricts the use of an entity to the enclosing declaration, and to extensions of that declaration that are in the same file. Use private access to hide the implementation details of a specific piece of functionality when those details are used only within a single declaration.


1 Answers

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.

like image 142
Kaiyuan Xu Avatar answered Sep 19 '22 15:09

Kaiyuan Xu