XCODE 偏好设置+数据归档化+私人通讯论

在这节中可以学习到XCODE中个人偏好和数据归档化两种数据持久方法:

(Todo: 数据归档化没有成功,不知道错在什么地方)
















数据归档必须将模型数据的头文件实现NSCoding协议,并在模型数据代码文件中实现两个协议方法


#import "TXContact.h"


@implementation TXContact


- (id)initWithCoder:(NSCoder *)aDecoder
{
    if(self = [super init]){
        self.name = [aDecoder decodeObjectForKey:@"name"];
        self.phone = [aDecoder decodeObjectForKey:@"phone"];
    }
    return self;
}


- (void)encodeWithCoder:(NSCoder *)encoder
{
    [encoder encodeObject:self.name forKey:@"name"];
    [encoder encodeObject:self.phone forKey:@"phone"];
}


@end

------------------------------

#import "TXLoginViewController.h"
#import "MBProgressHUD+MJ.h"
#import "TXContactViewController.h"


@interface TXLoginViewController ()
@property (weak, nonatomic) IBOutlet UITextField *accountView;
@property (weak, nonatomic) IBOutlet UIButton *loginBtn;
@property (weak, nonatomic) IBOutlet UITextField *pwdView;
- (IBAction)RmbChange:(id)sender;
- (IBAction)AutoChange:(id)sender;
@property (weak, nonatomic) IBOutlet UISwitch *RmbSwitch;
@property (weak, nonatomic) IBOutlet UISwitch *AutoSwitch;
- (IBAction)login;


@end


@implementation TXLoginViewController




- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    NSLog(@"dddd");
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(accountPwdChange) name:UITextFieldTextDidChangeNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(accountPwdChange) name:UITextFieldTextDidChangeNotification object:self.pwdView];
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    
    BOOL autoSwitch = [defaults boolForKey:@"AutoSwitch"];
    BOOL rmbSwitch = [defaults boolForKey:@"RmbSwitch"];
    NSString *account = [defaults objectForKey:@"account"];
    NSString *pwd = [defaults objectForKey:@"pwd"];
    
    self.AutoSwitch.on = autoSwitch;
    self.RmbSwitch.on = rmbSwitch;
    self.accountView.text = account;
    self.pwdView.text = pwd;
    
    
    if(rmbSwitch){
        self.loginBtn.enabled = YES;
    }
    
    if (autoSwitch) {
        [self login];
    }
}


- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (void)accountPwdChange
{
    self.loginBtn.enabled = (self.accountView.text.length && self.pwdView.text.length);
}




- (IBAction)RmbChange:(id)sender {
    
    [self.view endEditing:YES];


    if(self.RmbSwitch.isOn == NO){
        self.AutoSwitch.on = NO;
    }
}


- (IBAction)AutoChange:(id)sender{
    [self.view endEditing:YES];
    
    if(self.AutoSwitch.isOn){
        self.RmbSwitch.on = YES;
    }
}


- (IBAction)login {
    if(![self.accountView.text isEqualToString:@"txj"]){
        [MBProgressHUD showError:@"Account is error"];
        return;
    }
    if(![self.pwdView.text isEqualToString:@"123"]){
        [MBProgressHUD showError:@"Password is error"];
        return;
    }
    
    [MBProgressHUD showMessage:@"Loading..."];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        [MBProgressHUD hideHUD];
        
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        
        [defaults setBool:self.RmbSwitch.isOn forKey:@"RmbSwitch"];
        [defaults setBool:self.AutoSwitch.isOn forKey:@"AutoSwitch"];
        
        if(self.RmbSwitch.isOn){
            [defaults setObject:self.accountView.text forKey:@"account"];
            [defaults setObject:self.pwdView.text forKey:@"pwd"];
        }else{
            [defaults setObject:nil forKey:@"account"];
            [defaults setObject:nil forKey:@"pwd"];
        }
        
        [defaults synchronize];


        
        [self performSegueWithIdentifier:@"contact" sender:nil];
        
    });
}


- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    TXContactViewController *vc = segue.destinationViewController;
    vc.navigationItem.title = [NSString stringWithFormat:@"%@的通讯录", self.accountView.text];
}
@end


#import "TXContactViewController.h"
#import "TXAddViewController.h"
#import "TXEditViewController.h"
#import "TXContact.h"


#define DATAPATH [[NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"contacts.data"]




@interface TXContactViewController () <UIActionSheetDelegate, TXAddViewControllerDelegate, TXEditViewControllerDelegate>
@property (nonatomic, strong) NSMutableArray *contacts;
- (IBAction)logout:(id)sender;
@end


@implementation TXContactViewController




- (void)viewDidLoad
{
    [super viewDidLoad];
    
    NSLog(@"%@--------", DATAPATH);
    
}


- (NSMutableArray *)contacts
{
    if(_contacts == nil)
    {
        _contacts = [NSKeyedUnarchiver unarchiveObjectWithFile:DATAPATH];
        if(_contacts == nil)
        {
            _contacts = [NSMutableArray array];
        }
    }
    return _contacts;
}




#pragma mark - Table view data source




- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.contacts.count;
}




- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *ID = @"contact";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    /*
    if(!cell){
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:ID];
    }
    */
    
    TXContact *contact = self.contacts[indexPath.row];
    
    cell.textLabel.text = contact.name;
    cell.detailTextLabel.text = contact.phone;
    
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    
    return cell;
}


-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(editingStyle == UITableViewCellEditingStyleDelete){
        
        [self.contacts removeObjectAtIndex:indexPath.row];
        
        [self.tableView reloadData];
        
        [NSKeyedArchiver archiveRootObject:self.contacts toFile:DATAPATH];
    }
}




- (IBAction)logout:(id)sender
{
    NSString *title = @"确定要注销吗?";
    NSString *cfm = @"确定";
    NSString *cancel = @"取消";
    UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:title delegate:self cancelButtonTitle:cancel destructiveButtonTitle:cfm otherButtonTitles:nil, nil];
    
    [sheet showInView:self.view];
    
}


- (void) actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(buttonIndex != 0) return;
    
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    id vc = segue.destinationViewController;
    if ([vc isKindOfClass:[TXAddViewController class]]) {
        TXAddViewController *addvc = vc;
        addvc.delegate = self;
    }else if([vc isKindOfClass:[TXEditViewController class]]){
        TXEditViewController *editvc = vc;
        NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
        TXContact *contact = self.contacts[indexPath.row];
        editvc.contact = contact;
        editvc.delegate = self;
    }
}


- (void)addViewAddContact:(TXContact *)contact
{
    [self.contacts addObject:contact];
    
    [self.tableView reloadData];
    
    [NSKeyedArchiver archiveRootObject:self.contacts toFile:DATAPATH];
}


-(void)editViewControllerEditContact:(TXContact *)contact
{
    [self.tableView reloadData];
    
    [NSKeyedArchiver archiveRootObject:self.contacts toFile:DATAPATH];
}


@end

----------------------------

#import "TXAddViewController.h"
#import "TXContact.h"


@interface TXAddViewController ()
@property (weak, nonatomic) IBOutlet UITextField *nameView;
@property (weak, nonatomic) IBOutlet UITextField *phoneView;
@property (weak, nonatomic) IBOutlet UIButton *saveBtn;
- (IBAction)save;


@end


@implementation TXAddViewController


- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChanged) name:UITextFieldTextDidChangeNotification object:self.nameView];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChanged) name:UITextFieldTextDidChangeNotification object:self.phoneView];
}


- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


- (void)textChanged
{
    self.saveBtn.enabled = (self.nameView.text.length && self.phoneView.text.length);
}


- (IBAction)save {
    [self.navigationController popViewControllerAnimated:YES];
    
    
    if ([self.delegate respondsToSelector:@selector(addViewAddContact:)]) {
        TXContact *contact = [[TXContact alloc] init];
        contact.name = self.nameView.text;
        contact.phone = self.phoneView.text;
        
        [self.delegate addViewAddContact:contact];
    }
    
}
@end


#import "TXEditViewController.h"
#import "TXContact.h"


@interface TXEditViewController ()
@property (weak, nonatomic) IBOutlet UITextField *nameView;
@property (weak, nonatomic) IBOutlet UITextField *phoneView;
@property (weak, nonatomic) IBOutlet UIButton *saveBtn;
@property (weak, nonatomic) IBOutlet UIBarButtonItem *editBtn;
- (IBAction)edit:(id)sender;
- (IBAction)save;


@end


@implementation TXEditViewController


- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.nameView.text = self.contact.name;
    self.phoneView.text = self.contact.phone;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChanged) name:UITextFieldTextDidChangeNotification object:self.nameView];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChanged) name:UITextFieldTextDidChangeNotification object:self.phoneView];
}


- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


-(void)textChanged
{
    self.saveBtn.enabled = (self.nameView.text.length && self.phoneView.text.length);
}




- (IBAction)edit:(id)sender {
    if(!self.nameView.isEnabled)
    {
        self.nameView.enabled = YES;
        self.phoneView.enabled = YES;
        self.saveBtn.enabled = YES;
        self.saveBtn.hidden = NO;
        
        [self.phoneView becomeFirstResponder];
        self.editBtn.title = @"取消";
    }
    else
    {
        self.nameView.text = self.contact.name;
        self.phoneView.text = self.contact.phone;
        
        self.nameView.enabled = NO;
        self.phoneView.enabled = NO;
        self.saveBtn.enabled = NO;
        self.saveBtn.hidden = YES;
        
        [self.view endEditing:YES];
        self.editBtn.title = @"编辑";
    }
}


- (IBAction)save {
    [self.navigationController popViewControllerAnimated:YES];
    
    if([self.delegate respondsToSelector:@selector(editViewControllerEditContact:)])
    {
        self.contact.name = self.nameView.text;
        self.contact.phone = self.phoneView.text;
        
        [self.delegate editViewControllerEditContact:self.contact];
    }
}
@end


多个控制器之间数据传递:

1,顺传:在模板控制器中设置一个模型,然你在源文控制器中通过prepareSega方法取得目标控制器,并将模型传递给目标控制器

2,逆传:可通过代理、通知、Block实现



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值