14.0~14.6 文件、文件夹的增删查等,NSCoding

来源:互联网 发布:seo关键词优化是什意思 编辑:程序博客网 时间:2024/06/08 08:59

14.0. IntroductionFiles and Folder Management

iOS 是基于OS X的,而OS X又是基于Unix。应用是不能访问整个目录结构的,他只活在自己的沙盒中,而且别的程序也不能访问你沙盒中得内容。每个应用都有自己的沙盒目录和子目录。当程序安装后,系统将为这个程序创建如下目录



Documents/

 This folder is the destination for all user-created content. Content that your app has populated, downloaded, or created should not be stored in this folder.


Library/

保存缓存文件和用户偏好设置等,一般情况下,这个目录本身并不直接包含文件,而是包含一些文件夹,这些文件夹来包含文件。


应用的根目录会包含几个文件夹,解释下:


Library/Caches/

包含一些缓存文件,iOS不会备份这里面的文件,当磁盘空间不够,而且你的程序不在运行时,iOS可能就会删除这里面的文件,所以不要让你的程序太依赖这里面的文件,在需要的时候可能重新创建这里面的文件。如果需要一直用这些文件,那么你该把它放在/tmp目录下

Library/Preferences/

偏好设置,iOS back up

Library/Application Support/

app创建的,不包含用户创建的,必须保存到这下面。iOS back up 。此目录并不是自动创建的,如果没有你需要自己创建。

tmp/

app创建的下载的临时文件。not back up by iOS。如果你的程序需要展示一些图片,你有不想每次都去重新下载,这里将是一个好地方让你保存这些照片。这里不要保存用户创建的文档或文件Make sure that you are not storing any user-created documents or files in this folder.

这些目录的作用你也了解了,下一步是如何找到这些目录--api

14.1. Finding the Paths of the Most Useful Folders on Disk

应该使用iOS SDK找到相应的目录,而不该直接认为他们在哪里

请使用相应的api获取你要的目录,比如Documents目录,不要想当然的认为他的名称就是Documents。

NSFileManager 提供了很多文件和文件夹相关的操作。在你的程序中,最好自己创建一个NSFileManager实例,而不要用defaultManager 方法获得的实例,因为它不是线程安全的。

查找目录使用这个方法URLsForDirectory:inDomains: 


-(void)testURLsForDirectory

{

    NSFileManager *fileManager = [[NSFileManageralloc] init];

    NSArray *urls = [fileManagerURLsForDirectory:NSDocumentDirectory

                                       inDomains:NSUserDomainMask];

    if ([urls count] > 0){

        NSURL *documentsFolder = urls[0];

        NSLog(@"%@", documentsFolder);

    } else {

        NSLog(@"Could not find the Documents folder.");

    }

}


打印:

2014-07-02 15:34:43.198 cookbook7_12[541:a0b] file:///Users/sunward/Library/Application%20Support/iPhone%20Simulator/7.0.3/Applications/A0131001-3A2B-421D-BA36-8667D155F685/Documents/


2014-07-02 15:36:55.597 cookbook7_12[219:907] file://localhost/var/mobile/Applications/19E5F719-0326-4788-B127-E618CC0C6523/Documents/


14.2. Writing to and Reading from Files

保存:writeToFile:atomically:encoding:error:


writeToFile  文件保存到哪里

atomically原子的,如果是YES,那么先保存到临时文件,然后再把临时文件移到目标文件,即先保证了文件内容正确,然后再保存到目标位置。所以如果保存过程中程序崩溃,下次进来可以继续保存

encoding  编码,一般式UTF8

error 有错误产生的话,传出来


-(void)testNSStringReadWrite

{

    NSString *filePath = [NSTemporaryDirectory()stringByAppendingPathComponent:@"MyFile.txt"];

    if ([self writeText:@"Hello, World!"toPath:filePath]){

        NSString *readText = [self readTextFromPath:filePath];

        if ([readText length] > 0){

            NSLog(@"Text read from disk = %@", readText);

        } else {

            NSLog(@"Failed to read the text from disk.");

        }

    } else {

        NSLog(@"Failed to write the file.");

    }

}


- (BOOL) writeText:(NSString *)paramText toPath:(NSString *)paramPath{

    return [paramText writeToFile:paramPath

                      atomically:YES

                         encoding:NSUTF8StringEncoding

                           error:nil];

}


- (NSString *) readTextFromPath:(NSString *)paramPath{

    return [[NSString alloc]initWithContentsOfFile:paramPath

                                          encoding:NSUTF8StringEncoding

                                              error:nil];

}


打印:

2014-07-02 16:41:05.648 cookbook7_12[242:907] Text read from disk = Hello, World!


当然了,你也可以用URL来表示文件路径,相应的方法是

writeToURL:atomically:encoding:error:

initWithContentsOfFile: encoding: error:

foundation中其他的一些类也跟NSString一样有相应的保存,读取方法。

NSArray在保存数据时,其只能包含以下类型对象

• NSString
• NSDictionary

 • NSArray
• NSData
• NSNumber
• NSDate

如果array中有其他对象,那么在保存时将会失败,因为保存时会先检查下所有对象是不是上面所列的对象。因为如果不是上面所列的对象,OC runtime 将不知道如何来保存这个对象


NSDictionary也有非常相似的接口,所能保存的对象也跟NSArray一样。


好吧,这几个高级类我知道怎么保存读取了,那如果是字符数组呢?

数组可以先用NSData封装起来,然后保存,读取,不是吗


14.3. Creating Folders on Disk

创建文件夹

-(void)testCreateDirectory

{

    NSFileManager *fileManager = [[NSFileManageralloc] init];

    NSString *tempDir =NSTemporaryDirectory();

    NSString *imagesDir = [tempDir stringByAppendingPathComponent:@"images"];

    NSError *error = nil;

    if ([fileManager createDirectoryAtPath:imagesDir

               withIntermediateDirectories:YES

                               attributes:nil

                                    error:&error]){

        NSLog(@"Successfully created the directory.");

    } else {

        NSLog(@"Failed to create the directory. Error = %@", error);

    }

}


打印:

2014-07-02 17:05:38.835 cookbook7_12[265:907] Successfully created the directory.

2014-07-02 17:05:42.889 cookbook7_12[265:907] Successfully created the directory.

2014-07-02 17:05:57.985 cookbook7_12[265:907] Successfully created the directory.


我点了3次,居然3次创建成功,本以为从第2次开始会失败的


createDirectoryAtPath将要被创建的目录

withIntermediateDirectories如果是YES,如果最终目录的父(父父....)目录不存在,则创建

attributes文件夹的一些属性,比如修改时间啊,创建时间啊等等,不过简单处理,传nil就可

error 错误信息


14.4. Enumerating Files and Folders

枚举文件,文件夹

-(void)testContentsOfDirectory{

    NSFileManager *fileManager = [[NSFileManageralloc] init];

    NSString *bundleDir = [[NSBundle mainBundle] bundlePath];

    NSError *error = nil;

    NSArray *bundleContents = [fileManager

                              contentsOfDirectoryAtPath:bundleDir

                              error:&error];

    if ([bundleContents count] > 0 && error == nil){

        NSLog(@"Contents of the app bundle = %@", bundleContents);

    }

    else if ([bundleContents count] == 0 && error == nil){

        NSLog(@"Call the police! The app bundle is empty.");

    }

    else {

        NSLog(@"An error happened = %@", error);

    }

}


打印:

真机上:

2014-07-02 17:29:52.874 cookbook7_12[281:907] Contents of the app bundle = (

    "Base.lproj",

    "IMG_0257.PNG",

    "Info.plist",

    "LaunchImage-568h@2x.png",

    "LaunchImage-700-568h@2x.png",

    "MySong.mp3",

    PkgInfo,

    "ResourceRules.plist",

    "Sample.m4v",

    "_CodeSignature",

    "cookbook7_12",

    "embedded.mobileprovision",

    "en.lproj",

    "test.jpeg"

)

模拟器上:

2014-07-02 17:31:00.754 cookbook7_12[715:c07] Contents of the app bundle = (

    "Assets.car",

    "Base.lproj",

    "cookbook7_12",

    "en.lproj",

    "Info.plist",

    "LaunchImage-568h@2x.png",

    "LaunchImage-700-568h@2x.png",

    "MySong.mp3",

    PkgInfo,

    "Sample.m4v",

    "test.jpeg",

    "test_cbr.mp3"

)

不过对于获取到的结果,我们很难知道哪个是文件,哪个是文件夹,为了获得更多的信息,我们换个接口

contentsOfDirec toryAtURL:includingPropertiesForKeys:options:error:.

contentsOfDirectoryAtURL //查询目录

includingPropertiesForKeys  //你希望返回哪些属性信息

NSURLIsDirectoryKey//是不是目录

NSURLIsReadableKey //你的应用能否访问这个url

NSURLCreationDateKey //创建时间

NSURLContentAccessDateKey //最后一次访问时间

NSURLContentModificationDateKey //最后修改时间

options //0 或者 NSDirectoryEnumerationSkipsHiddenFiles ,是否跳过隐藏文件

error //返回错误信息

-(void)testContentsOfAppBundle{

    NSArray *itemsInAppBundle = [self contentsOfAppBundle];

    for (NSURL *item in itemsInAppBundle){

        [selfprintURLPropertiesToConsole:item];

    }

}


- (NSArray *) contentsOfAppBundle{

    NSFileManager *manager = [[NSFileManageralloc] init];

    NSURL *bundleDir = [[NSBundle mainBundle] bundleURL];

    NSArray *propertiesToGet = @[

                                NSURLIsDirectoryKey,

                                NSURLIsReadableKey,

                                NSURLCreationDateKey,

                                NSURLContentAccessDateKey,

                                NSURLContentModificationDateKey

                                ];

    NSError *error = nil;

    NSArray *result = [manager contentsOfDirectoryAtURL:bundleDir

                            includingPropertiesForKeys:propertiesToGet

                                               options:0

                                                 error:&error];

    if (error != nil){

        NSLog(@"An error happened = %@", error);

    }

    return result;

}


- (NSString *) stringValueOfBoolProperty:(NSString *)paramProperty

                                   ofURL:(NSURL *)paramURL{

    NSNumber *boolValue = nil;

    NSError *error = nil;

    [paramURL getResourceValue:&boolValue

                       forKey:paramProperty

                        error:&error];

    if (error != nil){

        NSLog(@"Failed to get property of URL. Error = %@", error);

    }

    return [boolValue isEqualToNumber:@YES] ?@"Yes" : @"No";

}


- (NSString *) isURLDirectory:(NSURL *)paramURL{

    return [selfstringValueOfBoolProperty:NSURLIsDirectoryKeyofURL:paramURL];

}


- (NSString *) isURLReadable:(NSURL *)paramURL{

    return [selfstringValueOfBoolProperty:NSURLIsReadableKeyofURL:paramURL];

}


- (NSDate *) dateOfType:(NSString *)paramType inURL:(NSURL *)paramURL{

    NSDate *result = nil;

    NSError *error = nil;

    [paramURL getResourceValue:&result

                       forKey:paramType

                        error:&error];

    if (error != nil){

        NSLog(@"Failed to get property of URL. Error = %@", error);

    }

    return result;

}


- (void) printURLPropertiesToConsole:(NSURL *)paramURL{

    NSLog(@"Item name = %@", [paramURLlastPathComponent]);

    NSLog(@"Is a Directory? %@", [selfisURLDirectory:paramURL]);

    NSLog(@"Is Readable? %@", [selfisURLReadable:paramURL]);

    NSLog(@"Creation Date = %@",[selfdateOfType:NSURLCreationDateKeyinURL:paramURL]);

    NSLog(@"Access Date = %@",[selfdateOfType:NSURLContentAccessDateKeyinURL:paramURL]);

    NSLog(@"Modification Date = %@",[selfdateOfType:NSURLContentModificationDateKeyinURL:paramURL]);

    NSLog(@"-----------------------------------");

}


打印:

2014-07-03 14:47:12.172 cookbook7_12[393:c07] Item name = Assets.car

2014-07-03 14:47:12.174 cookbook7_12[393:c07] Is a Directory? No

2014-07-03 14:47:12.174 cookbook7_12[393:c07] Is Readable? Yes

2014-07-03 14:47:12.176 cookbook7_12[393:c07] Creation Date = 2014-06-27 07:39:25 +0000

2014-07-03 14:47:12.176 cookbook7_12[393:c07] Access Date = 2014-06-27 07:39:25 +0000

2014-07-03 14:47:12.177 cookbook7_12[393:c07] Modification Date = 2014-06-27 07:39:25 +0000

2014-07-03 14:47:12.177 cookbook7_12[393:c07] -----------------------------------

2014-07-03 14:47:12.178 cookbook7_12[393:c07] Item name = Base.lproj

2014-07-03 14:47:12.178 cookbook7_12[393:c07] Is a Directory? Yes

2014-07-03 14:47:12.178 cookbook7_12[393:c07] Is Readable? Yes

2014-07-03 14:47:12.179 cookbook7_12[393:c07] Creation Date = 2014-06-27 06:46:16 +0000

2014-07-03 14:47:12.179 cookbook7_12[393:c07] Access Date = 2014-07-03 06:47:07 +0000

2014-07-03 14:47:12.180 cookbook7_12[393:c07] Modification Date = 2014-06-27 06:46:16 +0000

2014-07-03 14:47:12.180 cookbook7_12[393:c07] -----------------------------------

2014-07-03 14:47:12.180 cookbook7_12[393:c07] Item name = cookbook7_12

2014-07-03 14:47:12.181 cookbook7_12[393:c07] Is a Directory? No

2014-07-03 14:47:12.182 cookbook7_12[393:c07] Is Readable? Yes

2014-07-03 14:47:12.182 cookbook7_12[393:c07] Creation Date = 2014-07-03 06:46:53 +0000

2014-07-03 14:47:12.183 cookbook7_12[393:c07] Access Date = 2014-07-03 06:47:07 +0000

2014-07-03 14:47:12.183 cookbook7_12[393:c07] Modification Date = 2014-07-03 06:46:53 +0000

2014-07-03 14:47:12.184 cookbook7_12[393:c07] -----------------------------------

2014-07-03 14:47:12.184 cookbook7_12[393:c07] Item name = en.lproj

2014-07-03 14:47:12.185 cookbook7_12[393:c07] Is a Directory? Yes

2014-07-03 14:47:12.185 cookbook7_12[393:c07] Is Readable? Yes

2014-07-03 14:47:12.186 cookbook7_12[393:c07] Creation Date = 2014-06-27 06:21:08 +0000

2014-07-03 14:47:12.186 cookbook7_12[393:c07] Access Date = 2014-07-03 06:47:07 +0000

2014-07-03 14:47:12.187 cookbook7_12[393:c07] Modification Date = 2014-06-27 06:21:08 +0000

2014-07-03 14:47:12.187 cookbook7_12[393:c07] -----------------------------------

2014-07-03 14:47:12.188 cookbook7_12[393:c07] Item name = Info.plist

2014-07-03 14:47:12.188 cookbook7_12[393:c07] Is a Directory? No

2014-07-03 14:47:12.189 cookbook7_12[393:c07] Is Readable? Yes

2014-07-03 14:47:12.189 cookbook7_12[393:c07] Creation Date = 2014-06-27 08:00:03 +0000

2014-07-03 14:47:12.190 cookbook7_12[393:c07] Access Date = 2014-07-03 06:47:07 +0000

2014-07-03 14:47:12.190 cookbook7_12[393:c07] Modification Date = 2014-06-27 08:00:03 +0000

2014-07-03 14:47:12.191 cookbook7_12[393:c07] -----------------------------------

2014-07-03 14:47:12.191 cookbook7_12[393:c07] Item name = LaunchImage-568h@2x.png

2014-07-03 14:47:12.191 cookbook7_12[393:c07] Is a Directory? No

2014-07-03 14:47:12.192 cookbook7_12[393:c07] Is Readable? Yes

2014-07-03 14:47:12.192 cookbook7_12[393:c07] Creation Date = 2014-06-27 08:00:02 +0000

2014-07-03 14:47:12.193 cookbook7_12[393:c07] Access Date = 2014-06-27 08:00:02 +0000

2014-07-03 14:47:12.193 cookbook7_12[393:c07] Modification Date = 2014-06-27 08:00:02 +0000

2014-07-03 14:47:12.194 cookbook7_12[393:c07] -----------------------------------

2014-07-03 14:47:12.194 cookbook7_12[393:c07] Item name = LaunchImage-700-568h@2x.png

2014-07-03 14:47:12.195 cookbook7_12[393:c07] Is a Directory? No

2014-07-03 14:47:12.195 cookbook7_12[393:c07] Is Readable? Yes

2014-07-03 14:47:12.195 cookbook7_12[393:c07] Creation Date = 2014-06-27 08:00:02 +0000

2014-07-03 14:47:12.196 cookbook7_12[393:c07] Access Date = 2014-06-27 08:00:02 +0000

2014-07-03 14:47:12.196 cookbook7_12[393:c07] Modification Date = 2014-06-27 08:00:02 +0000

2014-07-03 14:47:12.197 cookbook7_12[393:c07] -----------------------------------

2014-07-03 14:47:12.197 cookbook7_12[393:c07] Item name = MySong.mp3

2014-07-03 14:47:12.198 cookbook7_12[393:c07] Is a Directory? No

2014-07-03 14:47:12.198 cookbook7_12[393:c07] Is Readable? Yes

2014-07-03 14:47:12.199 cookbook7_12[393:c07] Creation Date = 2014-06-27 06:22:19 +0000

2014-07-03 14:47:12.199 cookbook7_12[393:c07] Access Date = 2014-06-27 06:46:17 +0000

2014-07-03 14:47:12.200 cookbook7_12[393:c07] Modification Date = 2014-06-27 06:22:19 +0000

2014-07-03 14:47:12.200 cookbook7_12[393:c07] -----------------------------------

2014-07-03 14:47:12.200 cookbook7_12[393:c07] Item name = PkgInfo

2014-07-03 14:47:12.201 cookbook7_12[393:c07] Is a Directory? No

2014-07-03 14:47:12.201 cookbook7_12[393:c07] Is Readable? Yes

2014-07-03 14:47:12.202 cookbook7_12[393:c07] Creation Date = 2014-06-27 08:00:03 +0000

2014-07-03 14:47:12.202 cookbook7_12[393:c07] Access Date = 2014-06-27 08:00:03 +0000

2014-07-03 14:47:12.203 cookbook7_12[393:c07] Modification Date = 2014-06-27 08:00:03 +0000

2014-07-03 14:47:12.203 cookbook7_12[393:c07] -----------------------------------

2014-07-03 14:47:12.204 cookbook7_12[393:c07] Item name = Sample.m4v

2014-07-03 14:47:12.204 cookbook7_12[393:c07] Is a Directory? No

2014-07-03 14:47:12.205 cookbook7_12[393:c07] Is Readable? Yes

2014-07-03 14:47:12.205 cookbook7_12[393:c07] Creation Date = 2014-06-30 03:54:43 +0000

2014-07-03 14:47:12.205 cookbook7_12[393:c07] Access Date = 2014-06-30 03:54:43 +0000

2014-07-03 14:47:12.206 cookbook7_12[393:c07] Modification Date = 2014-06-30 03:54:43 +0000

2014-07-03 14:47:12.206 cookbook7_12[393:c07] -----------------------------------

2014-07-03 14:47:12.207 cookbook7_12[393:c07] Item name = test.jpeg

2014-07-03 14:47:12.207 cookbook7_12[393:c07] Is a Directory? No

2014-07-03 14:47:12.208 cookbook7_12[393:c07] Is Readable? Yes

2014-07-03 14:47:12.208 cookbook7_12[393:c07] Creation Date = 2014-07-02 06:09:20 +0000

2014-07-03 14:47:12.209 cookbook7_12[393:c07] Access Date = 2014-07-02 06:09:20 +0000

2014-07-03 14:47:12.209 cookbook7_12[393:c07] Modification Date = 2014-07-02 06:09:20 +0000

2014-07-03 14:47:12.210 cookbook7_12[393:c07] -----------------------------------

2014-07-03 14:47:12.210 cookbook7_12[393:c07] Item name = test_cbr.mp3

2014-07-03 14:47:12.210 cookbook7_12[393:c07] Is a Directory? No

2014-07-03 14:47:12.211 cookbook7_12[393:c07] Is Readable? Yes

2014-07-03 14:47:12.211 cookbook7_12[393:c07] Creation Date = 2014-06-27 06:21:08 +0000

2014-07-03 14:47:12.212 cookbook7_12[393:c07] Access Date = 2014-06-27 06:46:17 +0000

2014-07-03 14:47:12.212 cookbook7_12[393:c07] Modification Date = 2014-06-27 06:21:08 +0000


14.5. Deleting Files and Folders

删除文件,文件夹

-(void)testDeleteFileAndFolder

{

    NSString * txtPath = [NSTemporaryDirectory()stringByAppendingPathComponent:@"text"];

    NSLog(@"txtPath=%@",txtPath);

    self.fileManager = [[NSFileManageralloc] init];

    [selfcreateFolder:txtPath];

    [selfcreateFilesInFolder:txtPath];

    [selfenumerateFilesInFolder:txtPath];

    [selfdeleteFilesInFolder:txtPath];

    [selfdeleteFolder:txtPath];

}


/* Creates a folder at a given path */

- (void) createFolder:(NSString *)paramPath{

    NSError *error = nil;

    if ([self.fileManagercreateDirectoryAtPath:paramPath

                    withIntermediateDirectories:YES

                                    attributes:nil

                                         error:&error] == NO){

        NSLog(@"Failed to create folder %@. Error = %@",paramPath,error);

    }else{

        NSLog(@"succeeded to create folder");

    }

}


/* Creates 5 .txt files in the given folder, named 1.txt, 2.txt, etc */

- (void) createFilesInFolder:(NSString *)paramPath{/* Create 10 files */

    for (NSUInteger counter = 0; counter < 5; counter++){

        NSString *fileName = [NSString stringWithFormat:@"%lu.txt", (unsignedlong)counter+1];

        NSString *path = [paramPath stringByAppendingPathComponent:fileName];

        NSString *fileContents = [NSString stringWithFormat:@"Some text"];

        NSError *error = nil;

        if ([fileContents writeToFile:path

                          atomically:YES

                            encoding:NSUTF8StringEncoding

                               error:&error] == NO){

            NSLog(@"Failed to save file to %@. Error = %@", path, error);

        }else{

            NSLog(@"succeed to save file to %@",path);

        }

    }

}


/* Enumerates all files/folders at a given path */

- (void) enumerateFilesInFolder:(NSString *)paramPath{

    NSError *error = nil;

    NSArray *contents = [self.fileManagercontentsOfDirectoryAtPath:paramPath

                                                             error:&error];

    if ([contents count] > 0 && error == nil){

        NSLog(@"Contents of path %@ = \n%@", paramPath, contents);

    }

    else if ([contents count] == 0 && error == nil){

        NSLog(@"Contents of path %@ is empty!", paramPath);

    }

    else {

        NSLog(@"Failed to enumerate path %@. Error = %@", paramPath, error);

    }

}


/* Deletes all files/folders in a given path */

- (void)deleteFilesInFolder:(NSString *)paramPath{

    NSError *error = nil;

    NSArray *contents = [self.fileManagercontentsOfDirectoryAtPath:paramPath error:&error];

    if (error == nil){

        error = nil;

        for (NSString *fileName in contents){

            /* We have the file name, to delete it,

             we have to have the full path */

            NSString *filePath = [paramPath stringByAppendingPathComponent:fileName];

            if ([self.fileManagerremoveItemAtPath:filePath error:&error] == NO){

                NSLog(@"Failed to remove item at path %@. Error = %@",fileName,error);

            }else{

                NSLog(@"succeed to remove item at path %@",fileName);

            }

        }

    } else {

        NSLog(@"Failed to enumerate path %@. Error = %@", paramPath, error);

    }

}


/* Deletes a folder with a given path */

- (void) deleteFolder:(NSString *)paramPath{

    NSError *error = nil;

    if ([self.fileManagerremoveItemAtPath:paramPath error:&error] == NO){

        NSLog(@"Failed to remove path %@. Error = %@", paramPath, error);

    }else{

        NSLog(@"Succeed to remove path %@",paramPath);

    }

}


打印:

2014-07-03 15:33:42.771 cookbook7_12[1370:907] txtPath=/private/var/mobile/Applications/19E5F719-0326-4788-B127-E618CC0C6523/tmp/text

2014-07-03 15:33:42.776 cookbook7_12[1370:907] succeeded to create folder

2014-07-03 15:33:42.780 cookbook7_12[1370:907] succeed to save file to /private/var/mobile/Applications/19E5F719-0326-4788-B127-E618CC0C6523/tmp/text/1.txt

2014-07-03 15:33:42.783 cookbook7_12[1370:907] succeed to save file to /private/var/mobile/Applications/19E5F719-0326-4788-B127-E618CC0C6523/tmp/text/2.txt

2014-07-03 15:33:42.788 cookbook7_12[1370:907] succeed to save file to /private/var/mobile/Applications/19E5F719-0326-4788-B127-E618CC0C6523/tmp/text/3.txt

2014-07-03 15:33:42.792 cookbook7_12[1370:907] succeed to save file to /private/var/mobile/Applications/19E5F719-0326-4788-B127-E618CC0C6523/tmp/text/4.txt

2014-07-03 15:33:42.796 cookbook7_12[1370:907] succeed to save file to /private/var/mobile/Applications/19E5F719-0326-4788-B127-E618CC0C6523/tmp/text/5.txt

2014-07-03 15:33:42.799 cookbook7_12[1370:907] Contents of path /private/var/mobile/Applications/19E5F719-0326-4788-B127-E618CC0C6523/tmp/text = 

(

    "1.txt",

    "2.txt",

    "3.txt",

    "4.txt",

    "5.txt"

)

2014-07-03 15:33:42.803 cookbook7_12[1370:907] succeed to remove item at path 1.txt

2014-07-03 15:33:42.806 cookbook7_12[1370:907] succeed to remove item at path 2.txt

2014-07-03 15:33:42.809 cookbook7_12[1370:907] succeed to remove item at path 3.txt

2014-07-03 15:33:42.812 cookbook7_12[1370:907] succeed to remove item at path 4.txt

2014-07-03 15:33:42.814 cookbook7_12[1370:907] succeed to remove item at path 5.txt

2014-07-03 15:33:42.817 cookbook7_12[1370:907] Succeed to remove path /private/var/mobile/Applications/19E5F719-0326-4788-B127-E618CC0C6523/tmp/text



14.6. Saving Objects to Files

保存和读取新增类的对象到磁盘


首先你的类要遵守NSCoding 协议


看看你的类长什么样子,比如这样:

@interface Person :NSObject <NSCoding>


@property (nonatomic,copy) NSString *firstName;

@property (nonatomic,copy) NSString *lastName;


@end


NSString *const kFirstNameKey =@"FirstNameKey";

NSString *const kLastNameKey =@"LastNameKey";


@implementation Person


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

    [aCoder encodeObject:self.firstNameforKey:kFirstNameKey];

    [aCoder encodeObject:self.lastNameforKey:kLastNameKey];

}


- (instancetype)initWithCoder:(NSCoder *)aDecoder{

    self = [super init];

    if (self != nil){

        _firstName = [aDecoder decodeObjectForKey:kFirstNameKey];

        _lastName = [aDecoder decodeObjectForKey:kLastNameKey];

    }

    return self;

}


@end



测试一下保存和读取


-(void)testSaveYourClass

{

    /* Define the name and the last name we are going to set in the object */

    NSString *const kFirstName = @"Steven";

    NSString *const kLastName = @"Jobs";

    

    /* Determine where we want to archive the object */

    NSString *filePath = [NSTemporaryDirectory()stringByAppendingPathComponent:@"steveJobs.txt"];

    

    /* Instantiate the object */

    Person *steveJobs = [[Person alloc] init];

    steveJobs.firstName = kFirstName;

    steveJobs.lastName = kLastName;

    

    /* Archive the object to the file */

    [NSKeyedArchiverarchiveRootObject:steveJobs toFile:filePath];

    

    /* Now unarchive the same class into another object */

    Person *cloneOfSteveJobs =[NSKeyedUnarchiverunarchiveObjectWithFile:filePath];

    

    /* Check if the unarchived object has the same first name and last name

     as the previously-archived object */

    if ([cloneOfSteveJobs.firstName isEqualToString:kFirstName] && [cloneOfSteveJobs.lastNameisEqualToString:kLastName]){ 

NSLog(@"Unarchiving worked");

    } else {

        NSLog(@"Could not read the same values back. Oh no!");

    }

    

    /* We no longer need the temp file, delete it */

    NSFileManager *fileManager = [[NSFileManageralloc] init];

    [fileManager removeItemAtPath:filePath error:nil];

    

}


打印:

2014-07-03 16:41:55.705 cookbook7_12[1408:907] Unarchiving worked


0 0
原创粉丝点击