數據持久化(一)-----歸檔 讀寫 文件路徑

<pre>- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]autorelease];
// Override point for customization after application launch.
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];

/*HMTRootViewController * rootVC = [[HMTRootViewController alloc]init];
self.window.rootViewController = rootVC;
[rootVC release];*/

// 1.獲取沙盒文件的主路徑
NSLog(@"home = %@",NSHomeDirectory());

// 2.獲取Documents的路徑(獲取Library的路徑類似)
NSLog(@"documents = %@", [NSHomeDirectory() stringByAppendingString:@"/Documents"]);
NSLog(@"documents = %@", [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]);
NSLog(@"documents = %@",[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]);

// 3.獲取tmp的路徑(單獨的方法,與眾不同)
NSLog(@"tmp = %@",NSTemporaryDirectory());

// 4.應用程序包.app-----只有讀取的權利,沒有修改的權利
NSLog(@".app = %@",[[NSBundle mainBundle] bundlePath]);
NSLog(@"resource = %@",[[NSBundle mainBundle]resourcePath]);
NSLog(@".exec = %@",[[NSBundle mainBundle] executablePath]);

//[self simpleOperationOfApp];
[self complexOperationOfApp];
[self complexArrayOperationOfApp];

return YES;

}

pragma mark - 簡單的數據文件write/read

  • (void)simpleOperationOfApp{

pragma mark 字符串---txt

// 1.獲取存儲文件的上一級路徑
NSString * documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];

// 2.拼接一個完整的文件存儲路徑
NSString * filePath = [documentsPath stringByAppendingPathComponent:@"text.txt"];

// 3.write數據
NSString * saveString = @"我叫胡明濤";
[saveString writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];

// 4.從文件中read
NSString * readString = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
NSLog(@"%@",readString);

pragma mark 數組---plist

NSString * cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
NSString * arrayFilePath = [cachesPath stringByAppendingPathComponent:@"names.plist"];
NSArray * writeArray = @[@"吳凱",@"許珍珍",@"左友東"];
[writeArray writeToFile:arrayFilePath atomically:YES];

NSArray * readArray = [NSArray arrayWithContentsOfFile:arrayFilePath];
NSLog(@"%@",readArray);

pragma mark 字典---plist

NSString * tmpPath = NSTemporaryDirectory();
NSString * dicFilePath = [tmpPath stringByAppendingPathComponent:@"dic.plist"];
NSDictionary * writeDic = @{@"name": @"HMT",@"sex":@"female"};
[writeDic writeToFile:dicFilePath atomically:YES];

NSDictionary * readDic = [NSDictionary dictionaryWithContentsOfFile:dicFilePath];
NSLog(@"%@",readDic);

// 修改數據
[readDic setValue:@"humingtao" forKey:@"name"];
[readDic writeToFile:dicFilePath atomically:YES];
NSLog(@"%@",readDic);

pragma mark NSData

// 獲取圖片對象
UIImage * writeImage = [UIImage imageNamed:@"OJ2NMBNXQ1G5_20121120051201760"];

// 圖片對象轉變為NSData類型
NSData * writeData = UIImagePNGRepresentation(writeImage);

NSString * imageFilePath = [documentsPath stringByAppendingPathComponent:@"美女.png"];
[writeData writeToFile:imageFilePath atomically:YES];

NSData * readData = [NSData dataWithContentsOfFile:imageFilePath];
// imageNamed------圖片會存入緩存,下次加載很迅速,但是耗內存,圖片一大就嗝屁了
UIImage * readImage = [UIImage imageWithData:readData];
// 從文件路徑中找,調用一次就重新加載一次,只是顯示圖片,不加載到內存(后綴名不要加".")
[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"美女" ofType:@"png"]];
NSLog(@"%@",readImage);
NSLog(@"%@",[UIImage imageWithContentsOfFile:imageFilePath]);

}

pragma mark - 單個--復雜的數據對象write/read-------NSCoding協議

  • (void)complexOperationOfApp{

    UIButton * archiver = [UIButton buttonWithType:UIButtonTypeSystem];
    archiver.frame = CGRectMake(20, 100, 100, 40);
    [archiver setTitle:@"歸檔(序列化)" forState:UIControlStateNormal];
    [archiver addTarget:self action:@selector(onClickArchiverButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.window addSubview:archiver];

    UIButton * unArchiver = [UIButton buttonWithType:UIButtonTypeSystem];
    unArchiver.frame = CGRectMake(160, 100, 120, 40);
    [unArchiver setTitle:@"反歸檔(反序列化)" forState:UIControlStateNormal];
    [unArchiver addTarget:self action:@selector(onClickUnArchiverButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.window addSubview:unArchiver];
    }

pragma mark 對復雜的數據對象進行寫入操作.原理:復雜的數據對象序列化為NSData,將NSData寫入文件,實現數據持久化

  • (void)onClickArchiverButton:(UIButton *)button{

    /**

    • 1.自定義復雜的數據類型,例如ABPerson
    • (1)ABPerson必須實現NSCoding協議的方法
    • (2)ABPerson中的實例變量或屬性,也必須實現NSCoding協議的方法
    • (3)ABPerson中的基本數據類型沒有過多限制
    • 2.創建一個序列化工具對象
    • 3.先找路徑
    • 4.對復雜的數據類型對象進行序列化
    • 5.結束 finishEncoding
    • 6.NSData寫入
      */
      HMTABPerson * person = [[HMTABPerson alloc]init];
      person.name = @"HMT";
      person.age = 25;

    NSMutableData * archiverData = [NSMutableData data];
    NSKeyedArchiver * archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:archiverData];

    [archiver encodeObject:person forKey:@"PersonKey"];

    [archiver finishEncoding];

    NSString * documents = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
    NSString * filePath = [documents stringByAppendingPathComponent:@"person.data"];

    [archiverData writeToFile:filePath atomically:YES];

    [person release];
    [archiver release];

}

pragma mark 從文件中讀取數據來實例化復雜對象數據操作

  • (void)onClickUnArchiverButton:(UIButton *)button{

    /**

    • 1.先找路徑
    • 2.NSData讀出
    • 3.創建一個反序列化工具
    • 4.反序列化
    • 5.結束 finishDecoding
    • 6.操作對象了
      */
      NSString * documents = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
      NSString * filePath = [documents stringByAppendingPathComponent:@"person.data"];

    NSData * unarchiverData = [NSData dataWithContentsOfFile:filePath];

    NSKeyedUnarchiver * unarchiver = [[NSKeyedUnarchiver alloc]initForReadingWithData:unarchiverData];

    HMTABPerson * person = [unarchiver decodeObjectForKey:@"PersonKey"];

    [unarchiver finishDecoding];

    NSLog(@"%@",person.name);

    [unarchiver release];

}

pragma mark - 數組--復雜的數據對象write/read-------NSCoding協議

  • (void)complexArrayOperationOfApp{

    UIButton * archiver = [UIButton buttonWithType:UIButtonTypeSystem];
    archiver.frame = CGRectMake(20, 200, 100, 40);
    [archiver setTitle:@"歸檔(序列化)" forState:UIControlStateNormal];
    [archiver addTarget:self action:@selector(onClickArchiverArrayButton) forControlEvents:UIControlEventTouchUpInside];
    [self.window addSubview:archiver];

    UIButton * unArchiver = [UIButton buttonWithType:UIButtonTypeSystem];
    unArchiver.frame = CGRectMake(160, 200, 120, 40);
    [unArchiver setTitle:@"反歸檔(反序列化)" forState:UIControlStateNormal];
    [unArchiver addTarget:self action:@selector(onClickUnArchiverArrayButton) forControlEvents:UIControlEventTouchUpInside];
    [self.window addSubview:unArchiver];

}

pragma mark 寫入

  • (void)onClickArchiverArrayButton{

    NSMutableData * archiverData = [NSMutableData data];
    NSKeyedArchiver * archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:archiverData];

    HMTABPerson * person1 = [[HMTABPerson alloc]init];
    person1.name = @"陳鳳長";
    person1.age = 24;

    HMTABPerson * person2 = [[HMTABPerson alloc]init];
    person2.name = @"胡明濤";
    person2.age = 24;

    NSArray * personArray = @[person1,person2];

    [archiver encodeObject:personArray forKey:@"PersonArrayKey"];

    [archiver finishEncoding];

    NSString * tmpPath = NSTemporaryDirectory();
    NSString * filePath = [tmpPath stringByAppendingPathComponent:@"personArray.plist"];

    [archiverData writeToFile:filePath atomically:YES];

    [person1 release];
    [person2 release];
    [archiver release];

}

pragma mark 讀取

  • (void)onClickUnArchiverArrayButton{

    NSString * tmpPath = NSTemporaryDirectory();
    NSString * filePath = [tmpPath stringByAppendingPathComponent:@"personArray.plist"];

    NSData * unarchiverData = [NSData dataWithContentsOfFile:filePath];

    NSKeyedUnarchiver * unarchiver = [[NSKeyedUnarchiver alloc]initForReadingWithData:unarchiverData];

    NSArray * personArray = [unarchiver decodeObjectForKey:@"PersonArrayKey"];

    [unarchiver finishDecoding];

    HMTABPerson * person1 = [personArray objectAtIndex:0];
    HMTABPerson * person2 = [personArray objectAtIndex:1];

    NSLog(@"%@ %@",person1.name,person2.name);

    [unarchiver release];

}
HMTABPerson.h

import <Foundation/Foundation.h>

@interface HMTABPerson : NSObject <NSCoding>

@property (nonatomic,assign)int age;
@property (nonatomic,copy) NSString * name;

@end
HMTABPerson.m

import "HMTABPerson.h"

@implementation HMTABPerson

  • (void)dealloc{

    [_name release];
    [super dealloc];
    }

// 序列化,編碼

  • (void)encodeWithCoder:(NSCoder *)aCoder{

    [aCoder encodeObject:_name forKey:@"NameKey"];
    [aCoder encodeInt:_age forKey:@"AgeKey"];

}

// 反序列化,解碼

  • (id)initWithCoder:(NSCoder *)aDecoder{

    if (self = [super init]) {

      self.name = [aDecoder decodeObjectForKey:@"NameKey"];
      self.age  = [aDecoder decodeIntForKey:@"AgeKey"];
    

    }

    return self;
    }

@end</pre>

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容