chickenparm
chickenparm

Reputation: 1630

Type 'NSObject' has no member 'copy'

I just updated to Xcode 8 and now I'm getting the error in my project

Type 'NSObject' has no member 'copy'.

Before upgrading Xcode I was not getting this error.

Note: I'm still using Swift 2.3. I subclassed UILabel so that I could allow a user to copy text from a label on a long press. Below is my code. The error occurs on the line:

if action == #selector(NSObject.copy(_:))

Here is the full code:

class MCCopyableLabel: UILabel {

  override init(frame: CGRect) {
    super.init(frame: frame)
    sharedInit()
  }

  required init(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)!
    sharedInit()
  }

  func sharedInit() {
    userInteractionEnabled = true
    addGestureRecognizer(UILongPressGestureRecognizer(target: self, action: #selector(MCCopyableLabel.showMenu(_:))))
  }

  func showMenu(sender: AnyObject?) {
    becomeFirstResponder()
    let menu = UIMenuController.sharedMenuController()
    if !menu.menuVisible {
      menu.setTargetRect(bounds, inView: self)
      menu.setMenuVisible(true, animated: true)
    }
  }

  override func copy(sender: AnyObject?) {
    let board = UIPasteboard.generalPasteboard()
    board.string = text
    let menu = UIMenuController.sharedMenuController()
    menu.setMenuVisible(false, animated: true)
  }

  override func canBecomeFirstResponder() -> Bool {
    return true
  }

  override func canPerformAction(action: Selector, withSender sender: AnyObject?) -> Bool {
    if action == #selector(NSObject.copy(_:)) {
      return true
    }
    return false
  }
}

Upvotes: 6

Views: 3790

Answers (4)

mbonness
mbonness

Reputation: 1682

I had a similar error Type 'NSObject' has no member 'paste' after upgrading from Swift 2.2 to Swift 3, I was able to resolve it in the same way as Dan's comment above.

Swift 2

#selector(NSObject.paste(_:))

Swift 3

#selector(paste(_:))

Upvotes: 4

Huy Hoang
Huy Hoang

Reputation: 882

I had the same issue. I fixed it with:

#selector(UIResponderStandardEditActions.copy(_:))

Upvotes: 2

Satyanarayana
Satyanarayana

Reputation: 1067

try like this

#selector(UILabel.copy(_:))

Upvotes: 0

OOPer
OOPer

Reputation: 47896

The copy method does not take a parameter, so you may need to write it as:

#selector(NSObject.copy)

The notation #selector(NSObject.copy(_:)) works for a method with one parameter having no label.

Upvotes: 2

Related Questions