@Protocal: To create a
own protocal delegate
protocols declare
methods that can be implemented by any class. These classes are said
to conform to the protocol. They are like interfaces in
Java
Formal
protocols are declared with a
@protocol
block.- Informal protocols can be implemented in terms of a
@protocol
block with all the methods being@optional
or with a category ofNSObject
Delegates are very useful to control
transfer within the array of view controllers in app
manually. Using delegates you can manage the control flow very well.
here is small example of own
delegates....
- Create a protocol class.... (.h only)
file--->new --->objective
-c protocal (give name)
Ex:SampleDelegate
SampleDelegate.h
#import
<UIKit/UIKit.h>
@protocol SampleDelegate
// protocal name
@optional
#pragma
Home Delegate
-(NSString *)getViewName;
@end
2.
Import above protocol class in the class whom you want to make
delegate of another class. Here in my ex. I m using AppDelegate to
make delegate of The HomeViewController's Object.
also
add above DelegateName in Delegate Reference < >
ownDelegateAppDelegate.h
#import "SampleDelegate.h"
@interface ownDelegateAppDelegate
: NSObject <UIApplicationDelegate, SampleDelegate>
{
}
ownDelegateAppDelegate.m
//setDelegate
of the HomeViewController's object as
[homeViewControllerObject
setDelegate:self];
//add
this delegate method definition
-(NSString
*)getViewName
{
return
@"Delegate
Called";
}
HomeViewController.h
#import
#import "SampleDelegate.h"
// protocal header file.
@interface HomeViewController
: UIViewController
{
id<SampleDelegate>delegate;
}
@property(readwrite
,assign)
id<SampleDelegate>delegate;
//set the property
@end
HomeViewController.h
-(void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
UILabel *lblTitle
= [[UILabel alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
lblTitle.text =
[delegate
getViewName];
lblTitle.textAlignment = UITextAlignmentCenter;
[self.view addSubview:lblTitle];
}
No comments:
Post a Comment