lundi 30 mai 2016

iOS - Swift: Confused about the design pattern using protocol in a single viewcontroller app?

I've been working with swift for 2 years. But till now i'm still confuse about using Protocol, as its defination, protocol is a blueprint of methods, properties?

But be practical, why don't i pass one instance through classes or using global variables instead of using protocol?

For example i can do this:

Global variable:

var vc:UIViewController!

class vc:UIViewController
{
 var cc:ExClass!
 func viewDidLoad() {
  vc = self
  cc = ExClass()
  cc.anymethod()
 }
 func methodToCall() {
   print("hello")
 }
}
class ExClass() {
  func anymethod() {
     vc.methodToCall()
  }
}

Or i simply can pass the instance of UIViewController to ExClass, so ExClass can access to any properties, methods in UIViewController

I've tried to switch to use protocol.

However in example, if i have only 1 UIViewController like this, in this controller some parent views (one UIView for main screen, one UIView for setting), in each parent view has it own custom gesture, typer or some classes ...

And in these classes, i need to access to all the methods from parent views, and UIViewController also.

So, to get my app works, i have to pass the delegate through multiple levels classes, like from UIViewController to parent views, In custom gesture, i have delegate of UIViewController and its parent view also, in the other classes i have the same number of delegates .

It so complex and become a mess! And i really don't know about memory usage, of these design patterns, i want my app use the less memory as it can.

So what is a good design pattern or purpose of using protocol / delegate in this case?

Aucun commentaire:

Enregistrer un commentaire