1

I have a shared instance of a class in Swift that I'm using in Objective-C. I'm unable to create the shared instance and use the instance function. Here's my Swift code.

class VideoPlayerSignaler: NSObject {
    static let sharedInstance = VideoPlayerSignaler()

    let playerAction = Signal<PlayerAction>()

    private override init() {

    }

    func firePlayerAction(action: PlayerAction) {
        playerAction.fire(action)
    }
}

Here's my Objective-C code.

VideoPlayerSignaler *signaler = [VideoPlayerSignaler sharedInstance];

// This is the line that is producing the issue. 
// It's as if the signaler variable is a Class Instance
[signaler firePlayerAction: PlayerAction.Stop];

The error I'm producing states that firePlayerAction does not exist. In essence, Objective C believes the signaler variable to be a class instance.

What am I doing wrong and how do I fix it so that signaler is a shared instance of VideoPlayerSignaler?

10
  • 1
    If you post your code for the signal class as well as the firstPlayerAction in Objective-C, I may be able to help. Commented Oct 21, 2015 at 3:50
  • What issue does it produce? Commented Oct 21, 2015 at 3:55
  • I can give you the library code. https://github.com/artman/Signals Commented Oct 21, 2015 at 3:58
  • In fact, signaler here is really a "Class instance" Commented Oct 21, 2015 at 4:05
  • That's what I thought. XCode doesn't recognize the function or the instance variable. Commented Oct 21, 2015 at 4:09

1 Answer 1

2

There's nothing wrong with your Swift, or with how you access the singleton instance from ObjC — the problem is the enum value you're passing to it.

Presumably your enum declaration looks something like this:

enum PlayerAction: Int {
    case Stop, Collaborate, Listen // etc
}

To make your enum accessible to ObjC, you need to preface the declaration with @objc:

@objc enum PlayerAction: Int { /*...*/ }

This makes it appear as a Cocoa-style NS_ENUM declaration in ObjC, creating global symbols for case names by concatenating the Swift enum type's name with the case names:

typedef NS_ENUM(NSInteger, PlayerAction) {
    PlayerActionStop = 1,
    PlayerActionCollaborate,
    PlayerActionListen, // etc
};

So those names are what you should be passing when you call a method taking an enum value from ObjC:

[signaler firePlayerAction: PlayerActionStop]; // NOT PlayerAction.Stop

(The only docs I can find to cite for this are buried in the Attributes chapter in The Swift Programming Language — scroll down the to objc attribute.)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.