问题
I have two viewControllers
- ServiceProvider
- WorkLocation
In ServiceProvider I have one text field and a pick button.
When user click on pick button it will redirect to WorkLocation which has a list of locations.
When user select any location and then click on pick button from WorkLocation it will redirect back to ServiceProvider page with locationName and Id. And in ServiceProvider page locationName will be displayed in the text field which is already there.
To perform this I am using a protocol.
WorkLocation declaration:
#import <UIKit/UIKit.h>
#import "WorkDetailCell.h"
@protocol WorkLocationDetailViewDelegate <NSObject>
@required
-(void)organizationInfo:(NSString *) organization_id name:(NSString *)name;
@end
@interface WorkLocationDetailsViewController :UIViewController < UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate >
{
IBOutlet UITableView *workLocationTableView;
IBOutlet UISearchBar *workLocationSearchBar;
NSMutableArray *workDetailArray,*tempDataArray,*searchArray,*searchResultArray;
BOOL search;
}
@property (nonatomic,retain) id < WorkLocationDetailViewDelegate > delegate;
WorkLocation implementation:
-(IBAction)doneButtonClicked:(id)sender {
if (search==FALSE) {
NSLog(@"pick%d",[sender tag]);
NSLog(@"pick from temp");
NSDictionary *detailList=[tempDataArray objectAtIndex:[sender tag]];
[_delegate organizationInfo:detailList[@"organizationId"] name:detailList[@"organizationName"]];
} else {
NSLog(@"pick from search");
}
[self.navigationController popToRootViewControllerAnimated:YES];
}
and in ServiceProvider implementation file:
-(void)organizationInfo:(NSString*)organization_id name:(NSString *)name {
NSString *id=organization_id;
txtWorkLocation.text=name;
NSLog(@"%@ %@",organization_id,name);
}
Now when I came back from WorkLocation page this method is not called.
Declaration of ServiceProvider:
#import "WorkLocationDetailsViewController.h"
@class RadioButtonView;
@class WorkLocationDetailsViewController;
@protocol ServiceProviderProfileDelegate <NSObject>
@required
-(void)setProImages:(UIImage *)img;
@end
@interface ServiceProviderProfileViewController : UIViewController < UINavigationControllerDelegate, UIImagePickerControllerDelegate, RadioButtonDelegate, WorkLocationDetailViewDelegate >
{
NSString *gratuityStr,*paymentStr;
RadioButtonView *gratuityGroup,*paymentGroup;
IBOutlet UILabel *usernameLabel;
NSString *gratuitySelection,*receivePayment;
WorkLocationDetailsViewController *WorkVC;
}
回答1:
You have to set the ServiceProvider as delegate:
[WorkVC setDelegate:self];
回答2:
Why don't you use prepareForSegue: method to set text field of the destination view controller? This will make the communication between the view controllers in a standard way, and also reduce your coding effort.
Anyways, your code for implementing protocol looks ok. You need to check WorkVC is initiated before its delegate is set.
来源:https://stackoverflow.com/questions/20242854/how-to-use-protocol