問題: I get that with delegates you are delegating a task to another object. I guess I just don't understand why this is beneficial.app
最佳答案:
簡而言之, UITableView專一通用功能的實現 -- 你沒必要考慮如何才能讓table view滾動, 沒必要考慮記錄數過多怎麼辦(怎麼重用cell) 沒必要判斷是哪一個cell被點擊了. UITableView會告訴你, 你只要老老實實的實現它指定的接口, 作一個合格的delegate, 實現與UI無關的業務邏輯就好了. UITableView和Delegate(一般是ViewController) 各司其職 --- 作一件事, 並把它作好.less
原文以下:ui
[–]Eoghain 4 points 13 hours ago this
UITableView is the best example to think of here to get your head around it.code
What does the UITableView do?orm
And other things but that's a good place to start. Now you want to build an application that displays data in cells that can scroll on multiple pages without using delegates how would you create your own UITableView to be able to do this? I'm sure the basics above would be easy to implement and figure out, but what about these questions:接口
Is the version of UITableVIew that you are building even re-usable at this point? Not really, you'd have so much branching logic that your nice clean re-usable UITableView that just deals with laying things out on screen is a big buggy mess with no easy way to test it.ip
Now if you just focused only on the core features of what a UITableView does and instead delegated out the application logic to someone else you can see how clean and testable your UITableView becomes. All it cares about is putting some view it's given by someone else on screen at a specific location, allowing the views it's displaying to scroll, and telling whoever cares when a cell get's touched. This version of UITableView can be used by anyone for any purpose to display any data. It doesn't care what that data is, it doesn't care what happens when a cell is touched. It just delegates those decisions to someone else.ci
What delegates allow you to do is build re-usable code blocks that do "one" thing and do it well. They let the application logic be placed in less generic re-usable objects and allow developers to basically forget about all of the complexity of what the re-usable object is doing. How often do you concern yourself with the scrolling behavior of a UITableView? You don't, you know it'll work and do what it's told.get