Original blog, reproduced please indicate the source
Http://blog.csdn.net/hello_hwc
The understanding of an agent
What is an agent? As the name implies, the agent is to do their own tasks to others to do. Let the agent follow the supervision to hear some events, to implement some data sources. iOS developers should know that TableView has two properties, delegate and DataSource. This is the best embodiment of the agent, TableView at the beginning of the design does not know where this tableview will be placed in the future, what is stored, here the data source plays a key role: for the designer, I just based on the data source to generate the corresponding view, for the user, Only the data source needs to be populated. Instead, delegate gives the user an interface to respond to events, such as a row in the TableView being clicked, and so on.
Two-instance parsing
Using an example to analyze how a designer should design an agent, this example is mainly used to simulate some time-consuming tasks (with sleep substitution), then it is important to return the two events to the user to start the task and execute the task. First open Xcode to build a new project, select the Swift language, then just modify the default created Viewcontroller
(1) Define an abstract implementation scheme (protocol), which follows the implementation of two events
Protocol hwcsleepdelegate{
func Willstarttosleep ()
func Didfinishedsleep ()
}
(2) Define function classes to simulate long-time tasks
class hwcsleep{
var delegate:hwcsleepdelegate?
func starttosleep (time:UInt32) {
self. Delegate ?. Willstarttosleep()
NSLog("%@","before sleep in Starttosleep")
Sleep (time)
NSLog("%@","after sleep in Starttosleep")
self. Delegate ?. Didfinishedsleep()
}
}
(3) In the use of this function class, the implementation of proxy and Proxy methods
class Viewcontroller:uiviewcontroller,hwcsleepdelegate{
var sleepinstance:hwcsleep =hwcsleep()
Override func viewdidload () {
Super. Viewdidload ()
sleepinstance. Delegate = Self
sleepinstance. Starttosleep (2)
Additional setup after loading the view, typically from a nib.
}
func willstarttosleep () {
NSLog("%@","'ll start in Delegate method")
}
func didfinishedsleep () {
NSLog("%@","Finish Sleep in Delegate method")
}
}
Final output:
Swift Getting Started tutorial 18-proxy delegate