Xcode利用CoreData编成简易内置通讯录

最近看了一下苹果手机通讯录,感觉挺高端的,就随便做了一下它的那些效果,正好也可以复习复习CoreData
CoreData里的代码我就不说了,就是最基本的代码。里面分别有姓名,公司名,手机号码,和类型四种数据 四个都是字符串类型。

这里是显示页的ViewController

//
//  ViewController.m
//  TongXunLu
//
//  Created by ChuXiang on 15/12/25.
//  Copyright © 2015年 ChuXiang. All rights reserved.
//

#import "ViewController.h"
#import "AddContactViewController.h"
#import "SelectData.h"
#import "Contact.h"
#import "CoreDataManager.h"
@interface ViewController () <UITableViewDataSource,UITableViewDelegate, myDelegate>
@property (nonatomic,strong) UITableView *nameTable;
@property (nonatomic,strong) NSArray *sectionTitleArray;//总标题数组

@property (nonatomic,strong) NSMutableArray *sectionArray;//小标题数组
//全部数据数组
@property (nonatomic,strong) NSMutableArray *cellTextArray;// 装有cell的数组
@property (nonatomic,strong) SelectData *selectData; //CoreData的增删改查
@property (nonatomic,strong) NSArray *result; //从CoreData中取出总数据
@property (nonatomic,strong) CoreDataManager *manager;
@end

@implementation ViewController

- (void)viewDidLoad {
    [superviewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.navigationItem.title =@"所有联系人";
    self.selectData = [[SelectDataalloc] init];
    self.result = [self.selectDatagetAllData];

    self.cellTextArray = [NSMutableArrayarrayWithCapacity:0];

    self.navigationItem.rightBarButtonItem = [[UIBarButtonItemalloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAddtarget:selfaction:@selector(rightBarButtonDidPress:)];
    [self.viewaddSubview:self.nameTable];

    self.sectionTitleArray = [[NSArrayalloc] initWithObjects:@"A",@"B", @"C",@"D", @"E",@"F", @"G",@"H", @"I",@"J", @"K",@"L", @"M",@"N", @"O",@"P", @"Q",@"R", @"S",@"T", @"U",@"V", @"W",@"X", @"Y",@"Z", @"#",nil];
    self.sectionArray = [NSMutableArrayarrayWithCapacity:0];
    [selfDataAnalysis];

}

#pragma mark - 数据分析
- (void) DataAnalysis {
    self.selectData = [[SelectDataalloc] init];
    self.result = [self.selectDatagetAllData];
       for (int i =0; i < self.sectionTitleArray.count; i++) {
           for (Contact *contactin self.result) {
              if ([contact.firstStringisEqualToString:self.sectionTitleArray[i]]) {
                [self.sectionArrayaddObject:self.sectionTitleArray[i]];
                break;
            }
        }
    }
}

#pragma mark - 代理方法
- (void)updata {
    [self.sectionArrayremoveAllObjects];
    [selfDataAnalysis];
    [self.nameTablereloadData];
}

- (void)rightBarButtonDidPress:(id)sender {
    AddContactViewController  *addContact = [[AddContactViewControlleralloc] init];
    addContact.delegate =self;
    [self.navigationControllerpushViewController:addContact animated:YES];
}

#pragma mark - TableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSInteger num =0;
    for (Contact *contactin self.result) {
        if ([contact.firstStringisEqualToString:self.sectionArray[section]]) {
            num++;
        }
    }
    return num;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    returnself.sectionArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    [self.cellTextArrayremoveAllObjects];
    UITableViewCell *cell = [tableViewdequeueReusableCellWithIdentifier:@"UITableViewCellIdentifier"];
    for (Contact *contactin self.result) {
        if ([contact.firstStringisEqualToString:self.sectionArray[indexPath.section]]) {
            [self.cellTextArrayaddObject:contact.name];
        }
    }
    cell.textLabel.text =self.cellTextArray[indexPath.row];
    return cell;
}

- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return30;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *view = [[UIViewalloc] initWithFrame:CGRectMake(0,0, self.view.frame.size.width,self.view.frame.size.height)];
    view.backgroundColor = [UIColorcolorWithRed:214 /255.0 green:213 /255.0 blue:183 /255.0 alpha:1.0];
    UILabel *label = [[UILabelalloc] initWithFrame:CGRectMake(30,0, view.frame.size.width -30, 30)];
    label.text =self.sectionArray[section];
    label.font = [UIFontboldSystemFontOfSize:16];
    [view addSubview:label];
    return view;
}

#pragma mark - TableView Click 方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableViewcellForRowAtIndexPath:indexPath];

    AddContactViewController *addContact = [[AddContactViewControlleralloc] init];
    addContact.delegate =self;
//    addContact.idString = cell.textLabel.text;
    for (Contact *contactin self.result) {
        if ([contact.nameisEqualToString:cell.textLabel.text]) {
            addContact.idString = contact.name;
            addContact.idCompany = contact.company;
            addContact.phoneNumber = contact.phoneNumber;
        }
    }

    [self.navigationControllerpushViewController:addContact animated:YES];
}

#pragma mark - nameTable懒加载
- (UITableView *)nameTable {
    if (!_nameTable) {
        self.nameTable = [[UITableViewalloc] initWithFrame:CGRectMake(0,0, self.view.frame.size.width,self.view.frame.size.height)style:UITableViewStylePlain];
        self.nameTable.delegate =self;
        self.nameTable.dataSource =self;
        [self.nameTableregisterClass:[UITableViewCellclass] forCellReuseIdentifier:@"UITableViewCellIdentifier"];
        self.nameTable.bounces =NO;
    }
    return_nameTable;
}



这里是添加页的ViewController,添加页的视图我做的比较简单,大家如果想照原版1:1还原也不太麻烦~
//
//  AddContactViewController.m
//  TongXunLu
//
//  Created by ChuXiang on 15/12/25.
//  Copyright © 2015年 ChuXiang. All rights reserved.
//

#import "AddContactViewController.h"
#import "UIView+UIViewAdditions.h"
#import "SelectData.h"
@interface AddContactViewController ()
@property (nonatomic,strong) SelectData *selecData;
@property (nonatomic,strong) UIButton *deleteButton;
@property (nonatomic,strong) UIButton *receiveButton;
@end

@implementation AddContactViewController

- (void)viewDidLoad {
    [superviewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.title =@"新建联系人";
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItemalloc] initWithTitle:@"完成"style:UIBarButtonItemStyleDonetarget:selfaction:@selector(finishButtonDidPress:)];
    self.view.backgroundColor = [UIColorwhiteColor];

    self.selecData = [[SelectDataalloc] init];
    self.nameText = [[UITextFieldalloc] initWithFrame:CGRectMake(20,84, self.view.width -40, 50)];
    self.nameText.borderStyle =UITextBorderStyleBezel;
    self.nameText.placeholder =@"姓名";
    self.companyText = [[UITextFieldalloc] initWithFrame:CGRectMake(self.nameText.left,self.nameText.bottom +20, self.nameText.width,self.nameText.height)];
    self.companyText.placeholder =@"公司";
    self.companyText.borderStyle =UITextBorderStyleBezel;
    self.numberText =[[UITextFieldalloc] initWithFrame:CGRectMake(self.companyText.left,self.companyText.bottom +20, self.companyText.width,self.nameText.height)];
    self.numberText.placeholder =@"手机号码";
    self.numberText.borderStyle =UITextBorderStyleBezel;
    //判断从第一页是否传了字符串过来完成按钮的两种点击事件
    if (![self.idStringisEqualToString:@""]) {
        self.nameText.text =self.idString;
        self.companyText.text =self.idCompany;
        self.numberText.text =self.phoneNumber;
    }
    [self.viewaddSubview:self.nameText];
    [self.viewaddSubview:self.companyText];
    [self.viewaddSubview:self.numberText];

    self.deleteButton = [UIButtonbuttonWithType:UIButtonTypeSystem];
    [self.deleteButtonsetTitle:@"删除"forState:UIControlStateNormal];
    self.deleteButton.frame =CGRectMake(40,self.numberText.bottom +40, self.view.width -80, 20);
//    self.deleteButton.backgroundColor = [UIColor redColor];
    [self.deleteButtonsetTitleColor:[UIColorredColor] forState:UIControlStateNormal];
    [self.deleteButtonaddTarget:selfaction:@selector(deleteButtonDidPress:)forControlEvents:UIControlEventTouchUpInside];
    [self.viewaddSubview:self.deleteButton];


}

- (void)deleteButtonDidPress:(UIButton *)sender {
    [self.selecDatadeleteDataWith:self.nameText.text];
    [self.delegateupdata];
    [self.navigationControllerpopToRootViewControllerAnimated:YES];
}


- (void)finishButtonDidPress:(id)sender {
    //如果没传完成按钮则为添加作用
    if (self.idString ==NULL) {
        [self.selecDataaddContactWith:self.nameText.textandWith:self.companyText.textandWith:self.numberText.text];
    // 完成按钮为修改完成作用
    }else{
        [self.selecDatamodify:self.idStringwithNewName:self.nameText.textwithCompany:self.companyText.textwithPhoneNumber:self.numberText.text];
    }
    [self.delegateupdata];
    [self.navigationControllerpopToRootViewControllerAnimated:YES];
}

这个是我新建了一个类,继承于NSObject 里面就写了我需要对CoreData操作的方法,也减少一点代码量

//
//  SelectData.m
//  TongXunLu
//
//  Created by ChuXiang on 15/12/26.
//  Copyright © 2015年 ChuXiang. All rights reserved.
//

#import "SelectData.h"
#import "CoreDataManager.h"
#import "Contact.h"
@interface SelectData ()
@property (nonatomic,strong) CoreDataManager *coreDataManager;
@property (nonatomic,strong) NSArray *myData;
@end
@implementation SelectData
- (instancetype)init {
    self = [superinit];
    if (self) {
         self.coreDataManager = [CoreDataManagershareManager];
//            NSLog(@"%@", [self.coreDataManager applicationDocumentsDirectory]);
    }
    returnself;
}

//增加方法
- (void)addContactWith:(NSString *)name andWith:(NSString *)phoneNumber andWith:(NSString *)company {
    //插入实体:参数1:实体名参数2:数据管理器
    Contact *contact = [NSEntityDescriptioninsertNewObjectForEntityForName:@"Contact"inManagedObjectContext:self.coreDataManager.managedObjectContext];
    contact.name = name;
    contact.phoneNumber = phoneNumber;
    contact.company = company;

    //汉字转拼音
    NSString *chineseText = name;
    if ([chineseTextlength]) {
        NSMutableString *chinese = [[NSMutableStringalloc] initWithString:chineseText];
        if (CFStringTransform((__bridgeCFMutableStringRef)chinese, 0, kCFStringTransformMandarinLatin,NO)) {
            //范围截取
            NSRange range = {0,1};
            NSString *first = [[chinesesubstringWithRange:range] capitalizedString];
            contact.firstString = first;
        }
    }
    //保存到本地
    [self.coreDataManagersaveContext];
}

//获取全部数据
- (NSArray *)getAllData {
    // 发起一个数据请求
    NSFetchRequest *fetchRequst = [[NSFetchRequestalloc] init];
    //设置要请求的实体
    NSEntityDescription *entity = [NSEntityDescriptionentityForName:@"Contact"inManagedObjectContext:self.coreDataManager.managedObjectContext];
    [fetchRequst setEntity:entity];

    NSError *error =nil;
    self.myData = [self.coreDataManager.managedObjectContextexecuteFetchRequest:fetchRequst error:&error];
    if (self.myData ==nil) {
        NSLog(@"%@", error);
    }
    returnself.myData;
}

//删除方法
- (void)deleteDataWith:(NSString *)name {
    //发起一个数据请求
    NSFetchRequest *fetchRequest = [[NSFetchRequestalloc] init];
    //设置要请求的实体
    NSEntityDescription *entity = [NSEntityDescriptionentityForName:@"Contact"inManagedObjectContext:self.coreDataManager.managedObjectContext];
    [fetchRequest setEntity:entity];
    NSPredicate *predicate = [NSPredicatepredicateWithFormat:@"name = %@", name];
    [fetchRequest setPredicate:predicate];
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptoralloc] initWithKey:@"name"
                                                                  ascending:YES];
    [fetchRequest setSortDescriptors:[NSArrayarrayWithObjects:sortDescriptor, nil]];

    NSArray *data = [[NSArrayalloc] init];
    NSError *error =nil;
    data = [self.coreDataManager.managedObjectContextexecuteFetchRequest:fetchRequest error:&error];
    if (data ==nil) {
        NSLog(@"%@", error);
    }else {
        Contact *contact = [datalastObject];
        [self.coreDataManager.managedObjectContextdeleteObject:contact];
    }


    [self.coreDataManagersaveContext];
}

//修改方法
- (void)modify:(NSString *)name withNewName:(NSString *)newName withCompany:(NSString *)company withPhoneNumber:(NSString *)phone {
    //发起一个数据请求
    NSFetchRequest *fetchRequest = [[NSFetchRequestalloc] init];
    //设置要请求的实体
    NSEntityDescription *entity = [NSEntityDescriptionentityForName:@"Contact"inManagedObjectContext:self.coreDataManager.managedObjectContext];
    [fetchRequest setEntity:entity];
    NSPredicate *predicate = [NSPredicatepredicateWithFormat:@"name = %@", name];
    [fetchRequest setPredicate:predicate];
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptoralloc] initWithKey:@"name"
                                                                  ascending:YES];
    [fetchRequest setSortDescriptors:[NSArrayarrayWithObjects:sortDescriptor, nil]];

    NSArray *data = [[NSArrayalloc] init];
    NSError *error =nil;
    data = [self.coreDataManager.managedObjectContextexecuteFetchRequest:fetchRequest error:&error];
    if (data ==nil) {
        NSLog(@"%@", error);
    }else {
        Contact *contact = [datalastObject];
        contact.name = newName;
        contact.company = company;
        contact.phoneNumber = phone;
    }
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值