iOS数据持久化详解手机开发

// 
//  AppDelegate.m 
// 
// 
 
#import "AppDelegate.h" 
#import "Person.h" 
 
 
@interface AppDelegate () 
 
@end 
 
@implementation AppDelegate 
 
- (void)dealloc { 
    [_window release]; 
    [super dealloc]; 
} 
 
- (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]; 
 
 
    // 此函数可以通过制定的目录名称(第一个参数)和指定的作用域(第二个参数)以及 BOOL 类型的参数来确定是否返回完整路径,该函数的返回值类型为数组。 返回值之所以是数组因为,作用域里会有若干个相同的目录。 
    NSArray *filePaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    // 数据持久化常用的文件夹为 Documents 。 
    NSLog( @"Documents:%@", filePaths.firstObject ) ; 
 
    // 数据持久化常用的文件夹:tmp。但是重要的用户数据要存储在 Documents 文件夹中。 
    NSString *tmpFilePath = NSTemporaryDirectory(); 
    NSLog( @"tmp:%@", tmpFilePath ) ; 
 
    //应用程序在安装完成后会在对应的沙盒中产生一个.app文件(与之对应的类为 NSBundle ),工程中的资源文件会保存在这个.app文件中,此.app文件是只读的,我们通常叫他应用程序包。 
    NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"beutifuly" ofType:@"jpg"]; 
    NSLog( @"%@", imagePath ) ; 
 
    // 获取存储文件的 Documents 文件夹路径 
    NSString *docPath = filePaths.lastObject; 
    // text文件路劲的生成 
//    NSString *textFilePath = [docPath stringByAppendingString:@"/text.txt"]; 
    NSString *textFilePath = [docPath stringByAppendingPathComponent:@"text.txt"]; 
    NSLog( @"%@", textFilePath ); 
 
    // 简单对象写入文件 
    // 1、字符串写入文本文件 
    NSString *str = @"字符串写入文本文件"; 
    [str writeToFile:textFilePath atomically:YES encoding:NSUTF8StringEncoding error:nil]; 
 
    // 2、数组写入 
    NSString *arrayPath = [docPath stringByAppendingPathComponent:@"array.plist"]; 
    NSLog( @"%@", arrayPath ); 
    NSArray *array = @[@"哈哈", @"呵呵", @"嘿嘿",  @123]; 
    [array writeToFile:arrayPath atomically:YES]; 
 
    // 3、字典写入文件 
    NSString *dictPath = [docPath stringByAppendingPathComponent:@"dict.plist"]; 
    NSDictionary *dict = @{@"姓名":@"wang", @"性别":@"zhen", @"年龄":@12}; 
    [dict writeToFile:dictPath atomically:YES]; 
 
    // 4、NSData 写入文件(可以写入文本字符串,音频,视频,图片等等) 
    NSString *dataPath = [docPath stringByAppendingPathComponent:@"soYBAFVSEQ2IVhkZAA6sj5uH4wQAAAVIgLO86QADqyn976.m4a"]; 
    NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://fs.open.kugou.com/3a25cd93b65ac6611a2503dd8ad67976/55536711/G018/M08/0A/17/soYBAFVSEQ2IVhkZAA6sj5uH4wQAAAVIgLO86QADqyn976.m4a"]]; 
    [imageData writeToFile:dataPath atomically:YES]; 
    NSLog( @"%@", dataPath ); 
 
 
    // 使用 NSFileManager 来管理文件 
    // 1、创建文件夹 
    NSFileManager *filManager = [NSFileManager defaultManager]; 
    [filManager createDirectoryAtPath:[docPath stringByAppendingPathComponent:@"xxx"] withIntermediateDirectories:YES attributes:nil error:nil]; 
 
    // 应该先判断对应路劲的文件是否存在,如果存在,先读取文件内容,然后拼接新内容,再写入到文件中。 
    NSString *contentStr = nil; 
    // 通过文件管理对象判断指定文件路劲的文件是否存在 
    if ([filManager fileExistsAtPath:textFilePath]) { 
        contentStr = [NSString stringWithContentsOfFile:textFilePath encoding:NSUTF8StringEncoding error:nil]; 
    } 
    else { 
        contentStr = [NSString string]; 
    } 
    // 拼接新的字符串 
    contentStr = [contentStr stringByAppendingString:@"/n哈哈哈哈哈哈哈"]; 
    // 再将拼接完的字符串重新写入到文件中(这种方法太占内存,应该使用文件指针 NSFileHanle, 操作文件) 
    [contentStr writeToFile:textFilePath atomically:YES encoding:NSUTF8StringEncoding error:nil]; 
 
 
    // 复杂对象写入文件(归档和反归档) 
    NSMutableArray *personList = [NSMutableArray array]; 
    for (int i = 0; i < 100; i++) { 
        Person *aPerson = [[[Person alloc] init] autorelease]; 
        aPerson.name = @"wang"; 
        aPerson.gender = @"男"; 
        aPerson.age = 123; 
 
        [personList addObject:aPerson]; 
    } 
    // 指定文件路径 
    NSString *arcPath = [docPath stringByAppendingPathComponent:@"person.arc"]; 
    // 使用归档对象,归档对应的数据 
    [NSKeyedArchiver archiveRootObject:personList toFile:arcPath]; 
 
 
    // 使用反归档类,获取已归档的数据 
//    Person *person = [NSKeyedUnarchiver unarchiveObjectWithFile:arcPath]; 
//    NSLog( @"%@, %@, %ld", person.name, person.gender, person.age ) ; 
    NSArray *person = [NSKeyedUnarchiver unarchiveObjectWithFile:arcPath]; 
 
    NSLog( @"%@", person ) ; 
 
    // 返回当前应用程序的所在的主目录,即沙箱目录。 
    NSString *homePath = NSHomeDirectory(); 
    NSLog( @"%@", homePath ) ; 
 
 
 
 
 
    return YES; 
} 
 
- (void)applicationWillResignActive:(UIApplication *)application { 
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. 
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. 
} 
 
- (void)applicationDidEnterBackground:(UIApplication *)application { 
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. 
} 
 
- (void)applicationWillEnterForeground:(UIApplication *)application { 
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. 
} 
 
- (void)applicationDidBecomeActive:(UIApplication *)application { 
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. 
} 
 
- (void)applicationWillTerminate:(UIApplication *)application { 
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. 
} 
 
 
 
@end

// 
//  Person.h 
// 
// 
 
#import <Foundation/Foundation.h> 
 
 
 
@interface Person : NSObject<NSCoding> /// 如果一个自定义类的对象要支持归档,则需要遵守 NSCoding 协议,并实现编码和解码协议方法。 
 
@property (nonatomic, retain) NSString *name ; 
@property (nonatomic, retain) NSString *gender ; 
@property (nonatomic, assign) NSInteger age ; 
 
@end // Person

// 
//  Person.m 
// 
// 
 
#import "Person.h" 
 
 
 
@implementation Person 
 
 
// 编码协议是让当前类的对象通过固定的编码规则转成 NSData 类型的数据 
- (void)encodeWithCoder:(NSCoder *)aCoder { 
    [aCoder encodeObject:self.name forKey:@"NAME"]; 
    [aCoder encodeObject:self.gender forKey:@"GENDER"]; 
    [aCoder encodeInteger:self.age forKey:@"AGE"]; 
} 
 
 
// 解码方法,是在反归档的时候将NSData类型的数据转成当前类的对象时调用的。解码时用到的key要跟编码时指定的key保持一致。 
- (id)initWithCoder:(NSCoder *)aDecoder { 
    if (self = [super init]) { 
        self.name = [aDecoder decodeObjectForKey:@"NAME"]; 
        self.gender = [aDecoder decodeObjectForKey:@"GENDER"]; 
        self.age = [aDecoder decodeIntegerForKey:@"AGE"]; 
    } 
    return self; 
} 
 
 
 
 
 
 
 
 
 
@end

原创文章,作者:Maggie-Hunter,如若转载,请注明出处:https://blog.ytso.com/tech/aiops/3377.html

(0)
上一篇 2021年7月16日 14:29
下一篇 2021年7月16日 14:29

相关推荐

发表回复

登录后才能评论