How do I create delegates in Objective-C?

后端 未结 19 2513
一整个雨季
一整个雨季 2020-11-21 04:48

I know how delegates work, and I know how I can use them.

But how do I create them?

19条回答
  •  礼貌的吻别
    2020-11-21 05:02

    Maybe this is more along the lines of what you are missing:

    If you are coming from a C++ like viewpoint, delegates takes a little getting used to - but basically 'they just work'.

    The way it works is that you set some object that you wrote as the delegate to NSWindow, but your object only has implementations (methods) for one or a few of the many possible delegate methods. So something happens, and NSWindow wants to call your object - it just uses Objective-c's respondsToSelector method to determine if your object wants that method called, and then calls it. This is how objective-c works - methods are looked up on demand.

    It is totally trivial to do this with your own objects, there is nothing special going on, you could for instance have an NSArray of 27 objects, all different kinds of objects, only 18 some of them having the method -(void)setToBue; The other 9 don't. So to call setToBlue on all of 18 that need it done, something like this:

    for (id anObject in myArray)
    {
      if ([anObject respondsToSelector:@selector(@"setToBlue")])
         [anObject setToBlue]; 
    }
    

    The other thing about delegates is that they are not retained, so you always have to set the delegate to nil in your MyClass dealloc method.

提交回复
热议问题