7

Basically I want to know the difference between this

protocol ViewDelegate: class { 
  func someFunc()
}

and this

protocol ViewDelegate: NSObjectProtocol { 
  func someFunc()
}

Is there any difference ??

jscs
  • 63,694
  • 13
  • 151
  • 195
LeoGalante
  • 747
  • 6
  • 14
  • The one on top is an object, the one on the bottom is an object that also conforms to NSObjectProtocol. http://stackoverflow.com/a/24067969/1068243 – almas Apr 03 '17 at 22:40
  • 2
    @almas Neither is an object. The top is a protocol that can only be used by a class, not an enum or struct. – rmaddy Apr 03 '17 at 22:46
  • My bad. Top is a protocol that can be implemented by any object (but not struct), bottom is an extension of protocol NSObjectProtocol. – almas Apr 03 '17 at 22:56
  • What should one use when I need to make references weak for that protocol? – Akhil Dad Dec 17 '17 at 09:05

2 Answers2

6

Only Object or Instance type can conform to both type of protocol, where Structure and Enum can't conform to both the type

But the major difference is: If one declares a protocol like below means it is inheriting NSObjectProtocol

protocol ViewDelegate: NSObjectProtocol { 
    func someFunc()
}

if the conforming class is not a child class of NSObject then that class need to have the NSObjectProtocol methods implementation inside it. (Generally, NSObject does conform to NSObjectProtocol)

ex:

class Test1: NSObject, ViewDelegate {
   func someFunc() {
   }
   //no need to have NSObjectProtocol methods here as Test1 is a child class of NSObject
}

class Test2: ViewDelegate {
       func someFunc() {
       }
       //Have to implement NSObjectProtocol methods here
    }

If one declare like below, it means only object type can conform to it by implementing its methods. nothing extra.

protocol ViewDelegate: class { 
  func someFunc()
}
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
Santosh Sahoo
  • 134
  • 1
  • 5
-1

when confirming with class it means we only making in object type. So we can declare it as weak or strong But when confirming with NSObjectProtocol, we make it object type and also we can implement NSObjectProtocol method. which is already define in NSObjectProtocol delegate. So its up to you which way you want confirm your delegate