How Do We Use of Nsselectorfromstring in Swift

How do we use of NSSelectorFromString in swift?

The format of your Selector string is wrong. The Selector string for NSSelectorFromString has to look like the Objective-C signature.

Try:

let selector = NSSelectorFromString("testWithValue:value2:")

and your func has to be marked with @objc or your class has to be marked with @objcMembers.


How to get the Selector string:

Note: The preferred way to create a Selector in Swift is to use #selector as described by @DavidBerry in his answer because it gives you compile-time checking of the Selector.

If you still need NSSelectorFromString then this is how to find out the string:

After adding @objc to your function and compiling the project, click on the Related Items icon in Xcode in the upper left of the ViewController.swift window and select Generated Interface -> <ProjectName>-Swift.h. In there you will find your func's Objective-C interface:

- (void)testWithValue:(NSInteger)value value2:(NSInteger)value2;

then concatenate the parts that end with colons to create the Selector string: "testWithValue:value2:"

How do I convert objective-c `sortedArrayUsingSelector:NSSelectorFromString` to swift?

You can sort your array by property like this:

yourArray = yourArray.sort({ $0.yourString.lowercased() < $1.yourString.lowercased() })

The .lowercased() is to make sure that case sensitive won't be considered.

NSSelectorFromString with named parameters in Swift 3

In Swift 3, the first parameter name is part of the selector name, so you need to add WithArg if the first argument name is arg:

child.test("namedChildSelectorWithArg:", "daffodil")

Sending message to object using selector and NSSelectorFromString

[self performSelector:@selector(notifyViewControllers:) withObject: message];

Dynamically instanciating ObjC class in Swift (with NSClassFromString?)

Try this:

if let allocatedObject = NSClassFromString("MyClass")?.alloc() as? NSObject {
let selector: Selector = NSSelectorFromString("initWithApiKey:order:")
let methodIMP: IMP! = allocatedObject.method(for: selector)
let objectAfterInit = unsafeBitCast(methodIMP,to:(@convention(c)(AnyObject?,Selector,NSString,NSNumber)->NSObject).self)(allocatedObject,selector,"mykey", NSNumber(integerLiteral: 1))
}

More examples with details in my answer here

respondToSelector / performSelector with parameter from a string in Swift 3

The Swift method

func say(something:String)

is mapped to Objective-C as

- (void)sayWithSomething:(NSString * _Nonnull)something;

and therefore the correct selector would be

let selectorWithParam = NSSelectorFromString("sayWithSomething:" )

Using #selector is less error-prone:

let selectorWithParam = #selector(myClass.say(something:))

Sending message to object using selector and NSSelectorFromString

[self performSelector:@selector(notifyViewControllers:) withObject: message];


Related Topics



Leave a reply



Submit