Delegates vs. events in Cocoa Touch

后端 未结 3 1934
孤城傲影
孤城傲影 2021-01-19 01:21

I\'m writing my first iPhone app, and I\'ve been exploring the design patterns in Cocoa Touch and Objective-C. I come from a background of client-side web development, so I

3条回答
  •  旧巷少年郎
    2021-01-19 01:55

    Events and delegates have two different purposes, so you'll see both used.

    If you just want your button press to fire off a message, an event is fine. If you want your Done button press to validate the context of the text field before it is allowed to lose focus, you can use the textFieldShouldReturn delegate method to handle any validation and return NO if it doesn't validate.

    Delegates really allow you to change behaviour without subclassing. They're filled with should and did methods for this purpose. You implement these methods instead of overriding action methods when you want to validate, notify, or process before and/or after the action.

    If you find yourself thinking that you need to subclass a UIKit object, check its delegate methods first. Chances are there's already a place to put your custom behaviour.

提交回复
热议问题