iOS protocol

PROTOCOLS

  • Similar to @interface , but someone else does the implementing. 
  • Protocols are defined in a header file. 
eg:- @protocol ProtocolTest // Implementers must implement OtherDelegate as 
well.
       -(void)doSomething;//This should be implemented as methods are @required by default. 
@optional
-(int)getSomething; //Implementers do not have to implement this, as it is @optional
-(void)doSomethingWithArgument:(NSString*)argument

  • This has to be in ProtocolTest.h or the header file of the class which wants other classes to implemt it For example . UIScrollViewDelegate protocol is defined in UIScrollView.h  
  • Class then at their @interface add below code 
        #import "Foo.h"
        @interface MyClass :NSObject
        ....
        ....
        @end
  • Should implement all non - @optional methods
  • We can declare id variable with a protocol requirement 
       id obj = [[MyClass]alloc] init];

Use of protocol
  • It is mainly used in delegate and datasource
  • A delegate or datasource is defined as a weak @property 
@property (nonatomic, weak) id delegate;
This assumes that the object hat act as a delegate will outlive the delegator. eg:- UIViewController - a delegate
UIView - delegator.
Controllers always create and clean up the view object , because views are their minors.

@protocol TestDelagate
-(void)doSomething
@end
@interface MyView
@property (nonatomic,weak)  id delegate;
@end

-----------------
In implementation class you can do call this delegate method

@implementation MyView
 -(void)settings{
// this will the implemention class's doSomething.
  [delegate doSomething ];
}
@end 

In implementation class

@implementation MyViewController
-(void)viewDidLoad{
 myView.delegate = self;
}

-(void)doSomething{
//Do anything you want here. 
}


dataSource is just like delegate but it delegate the provisioning of data. Views commonly have datasource as views cannot own their data.

@class MyView - this is called as forward class as we are calling
@protocol TestDataSource
-(float)doSomething(MyView*)sender
@end
@interface MyView
@property (nonatomic,weak)  id delegate;
@end

In implementation class you can do call this delegate method

@implementation MyView
 -(void)settings{
// this will the implemention class's doSomething.
 float i =  [self.delegate doSomething ];
}
@end 

-----------------
In implementation class
@interface MyViewController
@end
@implementation MyViewController
-(void)viewDidLoad{
 myView.delegate = self;
}

-(float)doSomething(MyView*)sender{
//Do anything you want here.
return 10
}

No comments: