Monday, July 28, 2008

respondsToSelector

On p. 108, Hillegass mentions the respondToSelector method in NSObject. He says that an object calls this method on its delegate before sending it a message. Here is a simple illustration (no delegate yet). We don't do anything in the nib for this one. We just get an instance of MyReceiver, and through go_(), we ask whether it responds to the selector for a method. Here is the code:

class PyInvokeAppDelegate(NSObject):
def awakeFromNib(self):
self.myReceiver = MyReceiver.alloc().init()
self.go_(self)

def go_(self,sender):
NSLog("go_ %s" % sender.description())
flag = self.myReceiver.respondsToSelector_(
"absentMethod:")
NSLog("go_ returning %s" % flag)

class MyReceiver(NSObject):
def respondsToSelector_(self, s):
NSLog("Receiver respondsToSelector_ %s" % s)
super(MyReceiver,self).respondsToSelector_(s)

and the (edited) console log:

go_ < PyInvokeAppDelegate: 0x1f1dd80>
Receiver respondsToSelector_ absentMethod:
go_ returning None