最近課程設(shè)計(jì)寫了個(gè)iOS通訊錄,功能很簡單,就是增刪改查,再加上排序.
添加聯(lián)系人后使用的是使用的代理傳值,將聯(lián)系人信息傳到聯(lián)系人列表.
添加聯(lián)系人頁面為AddViewController,聯(lián)系人列表為ViewController
代理傳值共有六個(gè)步驟:
1拼缝、聲明協(xié)議(在AddViewController.h)
#import <UIKit/UIKit.h>
#pragma mark -- 第一步聲明協(xié)議與方法:
@protocol WxDelegate <NSObject>
- (void)WxDelegate:(NSMutableDictionary *)myDic;
@end
@interface AddViewController : UIViewController
2九孩、聲明代理變量(在AddViewController.h)
#pragma mark -- 第二部聲明代理人屬性:
@property(nonatomic, copy)NSMutableArray *myDic;
@property(nonatomic, assign)id<WxDelegate>delegate;
3、設(shè)置代理(在ViewController里面點(diǎn)擊添加聯(lián)系人,所以在ViewController.m中設(shè)置)
- (void)addAction:(UIBarButtonItem *)sender
{
AddViewController *addContactVC = [AddViewController new];
addContactVC.delegate = self;
UINavigationController *addContactNC = [[UINavigationController alloc] initWithRootViewController:addContactVC];
[self presentViewController:addContactNC animated:YES completion:nil];
}
4略号、通過代理變量調(diào)用協(xié)議方法(讓代理者開始執(zhí)行協(xié)議,在AddViewController.m)
- (void)saveAction:(UIBarButtonItem *)sender
{
Node *head = [Node new];
Node *newNode = head;
if(nil == newNode) {
printf("失敗");
exit(1);
}
// 獲取輸入內(nèi)容
newNode.phone = self.textField3.text;
newNode.introduce = self.textField2.text;
newNode.name = self.textField.text;
NSMutableDictionary *dic = [NSMutableDictionary dictionary];
// 獲取輸入內(nèi)容
[dic setObject:newNode.phone forKey:@"phone"];
[dic setObject:newNode.introduce forKey:@"portrait"];
[dic setObject:newNode.name forKey:@"name"];
[self dismissViewControllerAnimated:YES completion:nil];
[self.delegate WxDelegate:dic];
[self.navigationController popViewControllerAnimated:YES];
}
5、在代理(ViewController.m)中遵守協(xié)議
@interface ViewController ()
<UITableViewDelegate,UITableViewDataSource,
UISearchBarDelegate,UISearchDisplayDelegate,WxDelegate>
6基括、代理實(shí)現(xiàn)協(xié)議方法(在ViewController.m里面)
- (void)WxDelegate:(NSMutableDictionary *)myDic
{
ContactModel *model = [[ContactModel alloc]initWithDic:myDic];
[self.dataArr addObject:model];
_rowArr = [ContactDataHelper getFriendListDataBy:self.dataArr];
_sectionArr = [ContactDataHelper getFriendListSectionBy:[_rowArr mutableCopy]];
//更新首頁視圖:
[self.tableView reloadData];
}
這樣就可以把聯(lián)系人信息傳過去了