Gavin.han

致力于移动开发 技术改变生活

导航

ios数据处理 简单文件处理

Posted on 2012-11-23 17:26  gavin.han  阅读(597)  评论(0编辑  收藏  举报

1.文件路径的获取

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    NSString *homeDirectory = NSHomeDirectory();//获得Home路径,应用程序全路径
    NSString *fileDirectory = [homeDirectory stringByAppendingPathComponent:@"temp/app_data.plist"];
    
    //NSSearchPathForDirectoriesInDomains检索路径的方法
    NSArray *pathArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentDirectory = [pathArray objectAtIndex:0];
    NSString *fileDirectory2 = [documentDirectory stringByAppendingPathComponent:@"file.txt"];
    
    
    NSString *tempDirectory = NSTemporaryDirectory();
    NSString *file = [tempDirectory stringByAppendingPathComponent:@"file.txt"];

2.文件操作 

  NSFileManager常用的函数: 

    创建新文件。

- (BOOL)createFileAtPath:(NSString *)path contents:(NSData *)contents attributes:(NSDictionary *)attributes;   

        path :需要指定文件的全路径;contents,指定文件的内容;attributes:说明文件的属性。该函数的返回值为布尔型,用来表示创建成功或失败。

 

   创建路径。

- (BOOL)createDirectoryAtPath:(NSString *)path attributes:(NSDictionary *)attributes;

 

   删除文件。 

  - (BOOL)removeFileAtPath:(NSString *)path handler:(id)handler

handler:执行fileManager:willProcessPath:和fileManager:shouldProceedAfterError回调函数。handler也可以被置为nil,这样当删除文件出错的时候,会终止操作,并返回NO。 

 

 

以保存图片为例,主要用到了NSFileManager(使用这个类,可以很方便地访问文件。实现创建、删除、复制粘贴等) 

 注意:  1.使用textField的委托方法textFiledShouldReturn:,其协议是UITextFieldDelegate

           2. 设置textFileld的delegate属性

           3.设置textFileld的Return Key为Go

 

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    NSArray *paths= NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *filePath = [paths objectAtIndex:0];
    filePath = [filePath stringByAppendingPathComponent:[textField.text lastPathComponent]];
    
    NSLog(@"filePath:%@ ",filePath);
    
    //存储文件的全路径和数据
    NSData *imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:textField.text]];
    
    if (imageData)
    {
        UIImage *image = [UIImage imageWithData:imageData];
        [imageView setImage:image];
        [image release];
        
        //使用NSFileManager对象的createFileAtPath:contents:attributes:方法在指定的位置使用数据创建图片文件,如果需要改变文件的属性,创建包含对应键值的NSDictionary对象,传给attributes。
        [[NSFileManager defaultManager] createFileAtPath:filePath contents:imageData attributes:nil];   
        
    }
    
    [textField resignFirstResponder];
    return YES;

}

文件存放在Caches路径下: 

 

3.文件读写 

 (1)plist文件的读写 (有局限性,只有它支持的数据类型才可以被序列化)

    [testArray writeToFile:filePath atomically:YES]; 

    注:最后一个参数:如果是YES,写入文件的时候,将不会直接写入指定路径,而是会将数据写入一个“辅助文件”,写入成功后,再将辅助文件复制到指定路径。这样的话,实际操作的对象时辅助文件,从而可以避免原文件数据受到破坏。虽然可能增大系统的开销,但是为了保证数据的正确性,还是值得的。建议始终将改值设为YES。 

  (2)Archiver 归档数据的读写 (可以存储复杂的数据对象)

   类似“编码”、“解码”