Benjamin Netter
Benjamin Netter

Reputation: 1551

"unrecognized selector sent to instance" when setting a property on react-native

I'm trying to link my Swift view with my React-Native project. I figured out how to display it, but now when I'm trying to set a property, I'm having this error message:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[Switch setMessage:]: unrecognized selector sent to instance 0x7f96b270de70'

In my react-native code, I'm doing:

const SwitchNative = requireNativeComponent('Switch', Switch);

class Switch extends Component {
  render() {
    return (
        <SwitchNative message="message will be" style={this.props.style} />
    );
  }
}

Then doing this in my SwiftBridge:

// SwiftBridge.h

#import "RCTView.h"

@interface SwitchBridge : RCTView

  @property (nonatomic, assign) NSString *message;

@end

// SwiftBridge.m

#import "RCTBridgeModule.h"
#import "RCTViewManager.h"
#import "SwitchBridge.h"

@interface RCT_EXTERN_MODULE(SwitchManager, RCTViewManager)

  RCT_EXPORT_VIEW_PROPERTY(message, NSString)

@end

Then finally I have this in my Swift class Switch.swift:

...
public func setMessage(message: String) {
  NSLog("It's working well");
}
...

Not sure why it can't find my setMessage function.

Upvotes: 4

Views: 12627

Answers (3)

f4z3k4s
f4z3k4s

Reputation: 1249

For anyone might be searching for passing an array of objects from React-Native (I ran into this issue while doing that):

YourView.h:

@interface YourView : RCTView

@property (nonatomic, assign) NSMutableArray *markers;

@end

YourView.m:

...
RCT_CUSTOM_VIEW_PROPERTY(markers, NSMutableArray, YourView)
{
  [view setMarkers:json];
}

YourView.swift:

@objc(setMarkers:)
public func setMarkers(json: NSMutableArray) {
    
}

Upvotes: 0

Tirth
Tirth

Reputation: 7789

The correct syntax is now in swift,

@objc(setMessage:)
public func setMessage(message: String) {
  NSLog("It's working well");
}

This is change for Swift > 3.2, Mac High Sierra and React Native >= 0.43

Upvotes: 1

ide
ide

Reputation: 20838

React Native is trying to call -[Switch setMessage:] but you've defined -[Switch setMessage] without any parameters. Add a parameter to your Swift method signature:

public func setMessage(_ message: String)

You might also need to annotate your method with @objc depending on your version of Swift.

Upvotes: 8

Related Questions