如何使用协议

时间:2013-11-27 12:43:34

标签: ios iphone ios7 protocols

我有两个viewControllers

  • 的ServiceProvider
  • WorkLocation

ServiceProvider我有一个文本字段和一个选择按钮。 当用户点击选择按钮时,它将重定向到WorkLocation,其中包含location的列表。 当用户选择任何location然后点击WorkLocation中的选择按钮时,它会重定向回ServiceProviderlocationNameId。在ServiceProvider页面中locationName将显示在已存在的文本字段中。

要执行此操作,我使用的是协议。

WorkLocation声明:

 #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实施:

 -(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];
}

并在ServiceProvider实现文件中:

-(void)organizationInfo:(NSString*)organization_id name:(NSString *)name {
    NSString *id=organization_id;
    txtWorkLocation.text=name;
    NSLog(@"%@ %@",organization_id,name);
}

现在,当我从WorkLocation页面回来时,此方法未被调用。 声明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;
}

2 个答案:

答案 0 :(得分:0)

您必须将ServiceProvider设置为委托:

[WorkVC setDelegate:self];

答案 1 :(得分:0)

为什么不使用prepareForSegue:方法设置目标视图控制器的文本字段?这将以标准方式在视图控制器之间进行通信,并且还可以减少编码工作量。

无论如何,您实现协议的代码看起来还不错。您需要检查WorkVC是否在其委托设置之前启动。