1

I'm trying to learn the delegation process for Swift in Xcode 8.

I can get it working just fine, but have a question about the subclass in my delegate. Normally, in Objective-C, the subclass for this would be NSObject. I'm able to get it working with NSObject and AnyObject. I read a article about not crossing Objective-C because of performance. Does this really matter? If it's not a view or any other type of controller, what's the subclass in Swift for an object?

Is AnyObject the same as NSObject?

ViewController

import UIKit

class ViewController: UIViewController, TestDelegate {
    // init the delegate
    let theDelegate = TheDelegate ()

    @IBOutlet weak var label1: UILabel!

    @IBAction func button1(_ sender: Any) {
        // tell the delegate what to do
        theDelegate.run(add: 1)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        theDelegate.delegate = self
    }

    // the protocol
    func didTest(int: Int) {
        label1.text = "\(int)"
        print ("Got back from delegate \(int)")
    }
}

Object TestProtocol.swift

import Foundation

protocol TestDelegate: class {
    func didTest(int: Int)
}

class TheDelegate: AnyObject{
    weak var delegate: TestDelegate?
    func run(add: Int){
        let test = add + 1
        delegate?.didTest(int: test)
    }
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
iDev
  • 478
  • 1
  • 3
  • 24
  • 1
    There is no reason for `TheDelegate` to extend `AnyObject` (or any other class). – rmaddy Jul 05 '17 at 20:56
  • And nowhere are you subclassing a protocol. `ViewController` is conforming to a protocol but you do not have any subclasses of any delegate (at least not in the code you posted). – rmaddy Jul 05 '17 at 20:57
  • Following on from @rmaddy, you appear to be confusing terminology: `NSObject` (the class) is not a subclass of anything, rather it is *superclass* of most Objective-C objects (and you and ignore the ones for which it isn't for the moment). – CRD Jul 05 '17 at 21:12
  • There is also `NSObject`, *the protocol*, and `NSObject` the class conforms to it. Swift's `AnyObject` is also a protocol and it and the `NSObject` protocol, not class, have similar meaning/purpose. – CRD Jul 05 '17 at 21:16

1 Answers1

0

There is no reason to subclass AnyObject, since everything is an AnyObject just by existing (like object in Java).

NSObject is the old base class in Obj-C, so if you are wanting to have your protocol or class be seen in Obj-C code it must either be marked @objc or it must subclass NSObject.

So unless you are also using Obj-C in your program, then you don't need to subclass NSObject.

Look at Swift 3: subclassing NSObject or not? https://developer.apple.com/library/content/documentation/Swift/Conceptual/BuildingCocoaApps/MixandMatch.html

Garrigan Stafford
  • 1,331
  • 9
  • 20