码迷,mamicode.com
首页 > 移动开发 > 详细

iOS中的 沙盒文件夹 (数据的写入和读取,归档和反归档)

时间:2015-09-13 23:11:26      阅读:1166      评论:0      收藏:0      [点我收藏+]

标签:

AppDelegate.m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    /**
    沙盒中文件夹:
     1.Documents : 存储长久保存的数据
     2.library:
        Caches:存放的缓存,比如:视频,音频,图片,小说等等
        Perferences:存储偏好设置,比如:应用程序是否是第一次启动
        保存用户名和密码.
     3.tmp:存储临时文件,比如:下载的zip包,解压后直接删除.
     */
    
   //1.获取沙盒文件路径
    NSString *homePath= NSHomeDirectory();
    NSLog(@"%@",homePath);
    
    //NSUserDefaults 直接操作 Preferences 文件夹
    /*
    NSUserDefaults *userdefaults = [NSUserDefaults standardUserDefaults];
    [userdefaults setBool:YES forKey:@"FirstLanch"];
    [userdefaults setObject:@"Leo" forKey:@"userName"];
    [userdefaults setObject:@"lanoulanou" forKey:@"password"];
    [userdefaults synchronize]; //立即同步
    */
    //1.需求:判断用户之前是否已经登录,如果登录则提示登录成功,否则提示输入用户名和密码,存储到本地
    //NSUserDefaults *userdefaults = [NSUserDefaults standardUserDefaults];
//    if (![userdefaults objectForKey:@"account"] || ![userdefaults objectForKey:@"password"]) {
//        //无效状体,此时需要提醒用户,输入用户名和密码
//        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"你之前没有登录" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"登录", nil];
//        //设置警示框样式
//        alertView.alertViewStyle = UIAlertViewStyleLoginAndPasswordInput;
//        [alertView show];
//        [alertView release];
//    }else{
//        //有效登录状体,提示用户,登录成功
//        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"你已经登录" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil];
//        [alert show];
//        [alert release];
//    }
    //2.应用程序包得路径
    NSString *bundlePath = [[NSBundle mainBundle] bundlePath];
    NSLog(@"%@",bundlePath);
    return YES;
}

//点击警示框的按钮触发的方法
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (buttonIndex) {
        case 1:
        {
        //获取警示框上得的输入框中的内容
            NSString *accout = [alertView textFieldAtIndex:0].text;
            NSString *password = [alertView textFieldAtIndex:1].text;
            //持久化处理
            NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
            //将用户名密码存储到沙盒中 Preferences 文件夹下
            [user setObject:accout forKey:@"account"];
            [user setObject:password forKey:@"password"];
            [user synchronize];
        }
            break;
            
        default:
            break;
    }
}
RootViewController.m
#import "RootViewController.h"

@interface RootViewController ()
@property (retain, nonatomic) IBOutlet UITextField *nameTextField;
@property (retain, nonatomic) IBOutlet UITextField *pswTextField;

@end

@implementation RootViewController
/**
 *文件读取支持的类型:(字符串,数组,字典,二进制数据 -- NSData)
 1.写入文件.
 writeToFile:atomically:--针对于 数组,字典,二进制数据
 
 writeToFile:atomically:encoding:error: --针对于字符串
 
 2.从文件中读取数据
 [类名 类名WithContentsOfFile:(文件路径)]; --- 针对于数组,字典,二进制数据
 [类名 类名WithContentsOfFile:encoding:error:]; --- 针对字符串
 
 3.VVVIP
 对于数组,字典大容器来说,想要实现文件读写,必须保证容器中的元素也必须是字符串,数组,字典,二进制数据类型之一.
 
 
 */



- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (IBAction)writeBtn:(id)sender {
//    //1.字符串写入文件
//    NSError *error = nil;
//    //先读取源文件中的内容
//    NSString *oldStr = [NSString stringWithContentsOfFile:[self filePath] encoding:NSUTF8StringEncoding error:nil];
//    //将原有数据与新数据拼接一起
//    
//    
//    
//    NSString *newStr = [oldStr stringByAppendingFormat:@"%@",self.nameTextField.text];
//    if (!newStr) {
//        newStr = self.nameTextField.text;
//    }
//   BOOL isSuccess = [newStr writeToFile:[self filePath] atomically:YES encoding:NSUTF8StringEncoding error:&error];
//    if (isSuccess) {
//        NSLog(@"写入成功");
//    }else{
//        NSLog(@"写入失败");
//    }
    //2.数组写入文件
//    NSArray *dataArr = @[self.nameTextField.text, self.pswTextField.text];
//    
//    
//    
//    BOOL isSuccess = [dataArr writeToFile:[self filePath] atomically:YES];
    
    //2.字典写入文件
    NSDictionary *dic = @{@"tf1":self.nameTextField.text,@"tf2":self.pswTextField.text};
    [dic writeToFile:[self filePath] atomically:YES];
    
   
    
}

- (IBAction)readBtn:(id)sender {
//    //1.字符串从文件中读取
//   NSString *text = [NSString stringWithContentsOfFile:[self filePath] encoding:NSUTF8StringEncoding error:nil];
//    //2.让第二个输入框显示
//    self.pswTextField.text = text;
    
    
    
//    NSArray *dataArr = [NSArray arrayWithContentsOfFile:[self filePath]];
//    //第一个输入框显示第二个输入框的内容,第二个输入框显示第一个输入框的内容
//    self.nameTextField.text = [dataArr lastObject];
//    self.pswTextField.text = dataArr[0];
    
    
    
     //3.字典从文件中读取数据
    NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:[self filePath]];
    self.nameTextField.text = [dic objectForKey:@"tf2"];
    self.pswTextField.text = [dic objectForKey:@"tf1"];
}

//获取文件路径
- (NSString *)filePath{
    //1.获取Document(存放持久保存的数据)文件夹路径
    //参数1:查找的文件路径
    //参数2:在那个域中查找
    //参数3:是否显示详细路径
   NSString *doucumentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    //2.拼接上文件路径
    NSString *filtPath = [doucumentsPath stringByAppendingPathComponent:@"Leo.txt"];
    NSLog(@"%@",filtPath);
    return filtPath;
}

- (void)dealloc {
    [_nameTextField release];
    [_pswTextField release];
    [super dealloc];
}
@end
SecondViewController.m
#import "SecondViewController.h"
#import "Contact.h"
@interface SecondViewController ()
@property (retain, nonatomic) IBOutlet UITextField *secondNameTFd;
@property (retain, nonatomic) IBOutlet UITextField *secondPwdTFd;

@end

@implementation SecondViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
//归档按钮
- (IBAction)archiveFile:(id)sender {
    Contact *contact = [[Contact alloc] initWithName:self.secondNameTFd.text gender:self.secondPwdTFd.text age:19 phoneNumber:@"332" motto:@"不成功便成仁"];
    //1.创建归档工具对象
    NSMutableData *mData =[NSMutableData data];
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:mData];
    //2.开始归档
    [archiver encodeObject:contact forKey:@"Leo"];
    //3.结束归档
    [archiver finishEncoding];
    
    //4.内存释放
    [contact release];
    [archiver release];
    //data写入文件
    BOOL isSuccess = [mData writeToFile:[self getFilePath] atomically:YES];
}
//反归档
- (IBAction)noArchiveFile:(id)sender {
    //1.Data从本地读取数据
    NSData *data = [NSData dataWithContentsOfFile:[self getFilePath]];
    //2.创建反归档工具
    NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
    //3.开始反归档
   Contact *contact = [unarchiver decodeObjectForKey:@"Leo"];
    //4.结束反归档
    [unarchiver finishDecoding];

    //释放
    [unarchiver release];
    
    //5.读取数据
    self.secondNameTFd.text = contact.phoneNumber;
    self.secondPwdTFd.text = contact.name;
}

//获取文件路径的方法
- (NSString *)getFilePath{
    //1.获取 Documents 文件夹路径
    NSString *doucumentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    //2.拼接上存储文件的路径
    NSString *filePath = [doucumentsPath stringByAppendingPathComponent:@"Leo.data"];
    NSLog(@"%@",filePath);
    return filePath;
}


- (void)dealloc {
    [_secondNameTFd release];
    [_secondPwdTFd release];
    [super dealloc];
}
@end
Contact.h

#import <Foundation/Foundation.h>

@interface Contact : NSObject<NSCoding>
@property (nonatomic, copy) NSString *name;
@property (nonatomic, copy) NSString *gender;
@property (nonatomic, assign) NSInteger age;
@property (nonatomic, copy) NSString *motto;
@property (nonatomic, copy) NSString *phoneNumber;


- (instancetype)initWithName:(NSString *)name gender:(NSString *)gender age:(NSInteger)age phoneNumber:(NSString *)phoneNumber motto:(NSString *)motto;
@end



Contact.m

#import "Contact.h"

@implementation Contact
- (instancetype)initWithName:(NSString *)name gender:(NSString *)gender age:(NSInteger)age phoneNumber:(NSString *)phoneNumber motto:(NSString *)motto{
    if (self = [super init]) {
        self.name = name;
        self.gender = gender;
        self.age = age;
        self.phoneNumber = phoneNumber;
        self.motto = motto;
    }
    return self;
}


/**
 *  当一个对象进行归档是,自动调用该方法,为该对象的实例变量进行归档操作.
 *
 *  @param aCoder <#aCoder description#>
 */
- (void)encodeWithCoder:(NSCoder *)aCoder{
    //内部,要对每一个实例变量进行归档操作
    [aCoder encodeObject:_name forKey:@"name"];
    [aCoder encodeObject:_gender forKey:@"gender"];
    [aCoder encodeObject:@(_age) forKey:@"age"];
    [aCoder encodeObject:_motto forKey:@"motto"];
    [aCoder encodeObject:_phoneNumber forKey:@"phoneNumber"];
}
//当对一个对象进行反归档操作时,自动调用该方法,为该方法的实例变量进行反归档操作
- (id)initWithCoder:(NSCoder *)aDecoder
{
    if (self = [super init]) {
        self.name = [aDecoder decodeObjectForKey:@"name"];
        self.gender = [aDecoder decodeObjectForKey:@"gender"];
        self.age = [[aDecoder decodeObjectForKey:@"age"] integerValue];
        self.motto = [aDecoder decodeObjectForKey:@"motto"];
        self.phoneNumber = [aDecoder decodeObjectForKey:@"phoneNumber"];
    }
    return self;
}

-(void)dealloc
{
    self.name = nil;
    self.gender = nil;
    self.phoneNumber = nil;
    self.motto = nil;
    [super dealloc];
}
@end

 

iOS中的 沙盒文件夹 (数据的写入和读取,归档和反归档)

标签:

原文地址:http://www.cnblogs.com/wohaoxue/p/4805721.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!