I have this function in Swift
class func someFunction(idValue: Int, completionHandler: #escaping (_ jsonData: JSON) -> ()) {
(...)
if (some validation) {
completionHandler(jsonData)
} else {
completionHandler(JSON.null)
}
}
Now I want to call that function from Objective-C. What I am doing is this:
[[ClassName new] someFunction:self.sesionId completionHandler:^{
}];
But is throwing "No visible #interface for 'ClassName' declares the selector 'someFunction:completionHandler:'
How can I call this function?
Essentially the NSObject is the base object type in Apple development.
The root class of most Objective-C class hierarchies, from which subclasses inherit a basic interface to the runtime system and the ability to behave as Objective-C objects.
Your class defines like that, using NSObject supper class (related to your requirements).
class ClassName: NSObject {
class func someFunction(idValue: Int, completionHandler: #escaping (_ jsonData: String) -> ()) {
}
}
call this function
[ClassName someFunctionWithIdValue:12 completionHandler:^(NSString * test) {
}];
In addition to inheriting from NSObject and declaring the class with #objc , Seems that #objc must be added to the func declaration for it to be seen in objective-c classes/files.
like so:
#objc class SomeClass:NSObject {
#objc func someFunction(_:Any) -> Bool {
return true
}
}
It then shows up in the autocomplete when calling as normal :
#import "PROJECT_Name-Swift.h"
#implementation SomeObjCClass
...
-(void)someObjCMethod{
SomeClass* instance = [[SomeClass alloc]init];
[instance someFunction:(id _Nonnull)]
}
...
#end
the presence of public keyword didn't seem to affect it either way
Related
I have a Swift function public func doSomething( aKey : String, completed: #escaping (AModel?, TagError?)->()) {} that needs to be exposed to Objective C code for consumption. I have created an Objective C class wrapper like
#objc
public func doSomethingObjCWrapper(aKey : String) {
anObject.doSomething(aKey: aKey) { (modelA, error) in
if let whtModel = modelA {
// All good
DispatchQueue.main.async {
print("ok")
}
} else {
print("\(error?.localizedDescription ?? "Unknown error")")
}
}
}
to be called from Objective C code. Whenever the code gets triggered, I will always get EXC_BAD_ACCESS error in anObject.doSomething line. Any lead will be much appreciated.
is anObject conform the NSObject protocol?
if not, you can try this way because of the root class of most Objective-C class hierarchies, from which subclasses inherit a basic interface to the runtime system and the ability to behave as Objective-C objects
Reference https://developer.apple.com/documentation/objectivec/nsobject
How can we call class functions with a dynamic class name?
Assume the following example where I have two class with methods with same signature
class Foo{
class func doSomething()
}
class Foobar {
class func doSomething()
}
class ActualWork{
//call following method with a variable type so that it accepts dynamic class name
func callDynamicClassMethod(x: dynamicClass)
x.doSomething()
}
How can this be implemented so that x accepts values at run time
Edit: Sorry, I missed to mention that I was looking for any other ways other than protocol oriented approach. This is more of an exploratory question to explore if there is a more direct approach/pods/libraries to achieve this.
I liked this question, because it made me to think a lit'bit outside of the box.
I'll answer it, by dividing it into a few parts.
First
call class functions
Class function is basically a Type methods, which can be achieved using the static word inside the class context.
Taking that into account, you can get a simple solution, using protocol and passing the class reference (conforming to that protocol) like this:
protocol Aaa{
static func doSomething();
}
class Foo : Aaa{
static func doSomething() {
print("Foo doing something");
}
}
class FooBar : Aaa{
static func doSomething() {
print("FooBar doing something");
}
}
class ActualWork{
//Using class (static) method
func callDynamicClassMethod <T: Aaa> (x: T.Type) {
x.doSomething();
}
}
//This is how you can use it
func usage(){
let aw = ActualWork();
aw.callDynamicClassMethod(x: Foo.self);
aw.callDynamicClassMethod(x: Foo.self);
}
Second
In case you don't really need the method on the class context, you may consider using instance methods. In that case the solution would be even simpler, like this:
protocol Bbb{
func doSomething();
}
class Bar : Bbb{
func doSomething() {
print("Bar instance doing something");
}
}
class BarBar : Bbb{
func doSomething() {
print("BarBar instance doing something");
}
}
class ActualWork{
//Using instance (non-static) method
func callDynamicInstanceMethod <T: Bbb> (x: T){
x.doSomething();
}
}
//This is how you can use it
func usage(){
let aw = ActualWork();
aw.callDynamicInstanceMethod(x: Bar());
aw.callDynamicInstanceMethod(x: BarBar());
}
Third
If you need to use the class func syntax, as OP originally did:
class func doSomething()
You CANNOT simply use a protocol. Because protocol is not a class...
So compiler won't allow it.
But it's still possible, you can achieve that by using
Selector with NSObject.perform method
like this:
class ActualWork : NSObject{
func callDynamicClassMethod<T: NSObject>(x: T.Type, methodName: String){
x.perform(Selector(methodName));
}
}
class Ccc : NSObject{
#objc class func doSomething(){
print("Ccc class Doing something ");
}
}
class Ddd : NSObject{
#objc class func doSomething(){
print("Ccc class Doing something ");
}
#objc class func doOther(){
print("Ccc class Doing something ");
}
}
//This is how you can use it
func usage() {
let aw = ActualWork();
aw.callDynamicClassMethod(x: Ccc.self, methodName: "doSomething");
aw.callDynamicClassMethod(x: Ddd.self, methodName: "doSomething");
aw.callDynamicClassMethod(x: Ddd.self, methodName: "doOther");
}
Generics and Protocol oriented programming will do the job:
protocol Doable {
static func doSomething()
}
class Foo: Doable {
static func doSomething() {
debugPrint("Foo")
}
}
class Foobar: Doable {
static func doSomething() {
debugPrint("Foobar")
}
}
class ActualWork {
func callDynamicClassMethod<T: Doable>(x: T.Type) {
x.doSomething()
}
}
let work = ActualWork()
work.callDynamicClassMethod(x: Foo.self)
work.callDynamicClassMethod(x: Foobar.self)
you can achieve this with help of Protocol
protocol common {
static func doSomething()
}
class Foo : common{
static func doSomething() {
print("Foo")
}
}
class Foobar : common {
static func doSomething() {
print("Foobar")
}
}
class ActualWork{
//call following method with a variable type so that it accepts dynamic class name
func callDynamicClassMethod(x: common.Type) {
x.doSomething()
}
}
let fooObj : common = Foo()
let Foobarobj : common = Foobar()
let workObk = ActualWork()
workObk.callDynamicClassMethod(x:Foo.self)
workObk.callDynamicClassMethod(x:Foobar.self)
I think, there are three solutions. I shared an sample below.
Use "protocol" that has "doSomething()" function requirements.
Create a function which gets function definition as a parameter.
Use reflection. you can use EVReflection that is good Api for reflection.
sample code:
protocol FooProtocol {
static func doSomething()
}
class Foo: FooProtocol {
class func doSomething() {
print("Foo:doSomething")
}
}
class Foobar: FooProtocol {
class func doSomething() {
print("Foobar:doSomething")
}
}
class ActualWork {
func callDynamicClassMethod<T: FooProtocol>(x: T.Type) {
x.doSomething()
}
func callDynamicClassMethod(x: #autoclosure () -> Void) {
x()
}
func callDynamicClassMethod(x: () -> Void) {
x()
}
}
ActualWork().callDynamicClassMethod(x: Foo.self)
ActualWork().callDynamicClassMethod(x: Foobar.self)
print("\n")
ActualWork().callDynamicClassMethod(x: Foo.doSomething())
ActualWork().callDynamicClassMethod(x: Foobar.doSomething())
print("\n")
ActualWork().callDynamicClassMethod(x: Foo.doSomething)
ActualWork().callDynamicClassMethod(x: Foobar.doSomething)
Looks like you are searching for duck typing, and this is harder to achieve in a statically typed language (with some exceptions, listed in the linked Wikipedia page).
This is because dynamically calling a method requires knowledge about the layout of the target object, thus either inheritance of the class declaring the method, or conformance to a protocol that requires that method.
Starting with Swift 4.2, and the introduction of dynamic member lookup, there is another approach to solve your problem, however it also involves some ceremony:
// This needs to be used as base of all classes that you want to pass
// as arguments
#dynamicMemberLookup
class BaseDynamicClass {
subscript(dynamicMember member: String) -> () -> Void {
return { /* empty closure do nothing */ }
}
}
// subclasses can choose to respond to member queries any way they like
class Foo: BaseDynamicClass {
override subscript(dynamicMember member: String) -> () -> Void {
if member == "doSomething" { return doSomething }
return super[dynamicMember: member]
}
func doSomething() {
print("Dynamic from Foo")
}
}
class Bar: BaseDynamicClass {
override subscript(dynamicMember member: String) -> () -> Void {
if member == "doSomething" { return doSomething }
return super[dynamicMember: member]
}
func doSomething() {
print("Dynamic from Bar")
}
}
func test(receiver: BaseDynamicClass) {
receiver.doSomething()
}
test(receiver: Bar()) // Dynamic from Bar
To conclude, in the current Swift version there is no way to have both the argument and the method dynamic, some common ground needs to be set.
I am having trouble calling a function in a swift file from an objective-c file where there is a closure in the swift function.
This is the Swift function
//In Utilities class
static func getString(query: NSString, completion: #escaping (_ response: NSString) -> Void) {
completion("hello")
}
This is how I try to call it in the objective-c class:
[Utilities getString:#"hi there" completion:^(NSString* response) {
NSLog(response);
}];
I'm getting the error 'No known class method for selector 'getString:completion:'
What is wrong with above?
Note: I am able to call a simpler method without the closure/completion bloc.
in swift class
static func myTest () {
print("function called")
}
called from objective-c class with:
[Utilities myTest];
SO the problem seems to relate to the closure syntax.
Surround the class with
#objcMembers class Utilities:NSObject {
or the function
#objc class func getString(query: NSString, completion: #escaping (_ response: NSString) -> Void) {
[Utilities getStringWithQuery:#"hi there" completion:^(NSString* response) {
NSLog(response);
}];
am exposing swift API's in Objective-C and the Objective-C runtime.
When i add "#objc" before the function throws an error "Method cannot be marked #objc because its result type cannot be represented in Objective-C"
My code is here
#objc public static func logIn(_ userId: String) -> User? { }
User is optional struct. how to solve this.
The key bit of information is this:
User is optional struct
If User is a struct, then it can't be represented in Objective-C, just the same as a Swift class that doesn't inherit from NSObject.
In order for the method logIn(_:) to be able to be marked #objc, then every type referenced in the method declaration has to be representable in Objective-C. You're getting the error message because User isn't.
To fix it, you're either going to have to change the declaration of User from this:
struct User {
// ...
}
...to this:
class User: NSObject {
// ...
}
...or redesign logIn(_:) so that it doesn't return a User.
You can find more information about this here. In particular, this answer offers the following potential solution:
The best thing i found was to wrap in a Box class
public class Box<T>: NSObject {
let unbox: T
init(_ value: T) {
self.unbox = value
}
}
Change the definition of your class as below
class User: NSObject {
}
In this way this class will be available in Objective-C
Your class or protocol, must be inherited (extended) by NSObject or anyother class in its hierarchy, containing your code (function) with #objc notation.
Example:
class TestClass {
public static func logIn(_ userId: String) -> User? { }
}
To use/declare #objc with this function, class must extend NSObject (or any other class in its hierarchy)
class TestClass {
#objc public static func logIn(_ userId: String) -> User? { }
}
Update:
struct may not work with optional value in Objective-C, as a work around, you should change User from struct to class
Try following code and see:
public class User : NSObject {
// Your code
}
public final class Manager : NSObject {
#objc public static func logIn(_ userId: String) -> User? {
return nil
}
}
Here is snapshot with editor
Only an NSObject-derived class type can be seen by Objective-C. Use:
class User : NSObject {
}
I have a swift protocol which i have defined for testing openUrl functionality in iOS. It looks something like this:
protocol URLOpener {
func open(_ url: URL, options: [String : Any], completionHandler completion: ((Bool) -> Void)?)
func canOpenURL(_ url: URL) -> Bool
}
extension UIApplication: URLOpener {}
Note that UIApplication is class is conformed to this protocol.
Now i have a class which takes an object URLOpener type to initilize that class
import Foundation
class GenericHandler : NSObject {
required init(urlOpener: URLOpener) {
super.init()
}
func aaa() {
NBLog("aaaaa")
}
}
I want to use this GenericHandler class from Objective C but i gives me an error that it could not find the initilizer.
GenericHandler *handler = [[GenericHandler alloc] initWithUrlOpener:[UIApplication sharedApplication]];
[handler aaa];
No visible #interface for 'GenericHandler' declares the selector 'initWithUrlOpener:'
However if i change the initizer so that it accepts String parameter then it starts to work fine.
import Foundation
class GenericHandler : NSObject {
required init(urlOpener: String) {
super.init()
}
func aaa() {
NBLog("aaaaa")
}
}
GenericHandler *handler = [[GenericHandler alloc] initWithUrlOpener:#"test"];
[handler aaa];
This just works fine. Can anyone guide me whats the issue withURLOpener protocol or how i can make it working with URLOpener parameter.
A bit late, but I just struggled with the same question.
You have to expose both the protocol and the init to Objective-C.
#objc protocol URLOpener {
func open(_ url: URL, options: [String : Any], completionHandler completion: ((Bool) -> Void)?)
func canOpenURL(_ url: URL) -> Bool
}
extension UIApplication: URLOpener {}
-
import Foundation
class GenericHandler : NSObject {
#objc required init(urlOpener: URLOpener) {
super.init()
}
func aaa() {
NBLog("aaaaa")
}
}
You can always check your generated header file to see if your Swift code is available in Objective-C. See the paragraph "Importing Swift into Objective-C" from the Apple docs.