iOS中的 沙盒文件夾 (數據的寫入和讀取,歸檔和反歸檔)

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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章