zoukankan      html  css  js  c++  java
  • ios 文件操作

    1.每个ios程序都有一个这样的目录:

    2.获取Documents目录:

        NSArray *path=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory=[path objectAtIndex:0];
    NSLog(@"%@",documentsDirectory);

    在末尾附加另一个字符串来创建文件名

    NSString *fname=[documentsDirectory stringByAppendingPathComponent:@"newFile.txt"];//完整路径

    3.获取tmp目录:

    NSString *temPath=NSTemporaryDirectory();


    4. 把2个textField的数据保存,下次打开时加载。

    -(NSString *)dataFilePath//返回文件路径
    {
    NSString *fileName=@"userdata.txt";
    NSArray *path=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentDirectory=[path objectAtIndex:0];
    return [documentDirectory stringByAppendingPathComponent:fileName];
    }

    文件操作

    -(IBAction)saveToFile
    {
    NSMutableArray *array=[[NSMutableArray alloc] init];
    [array addObject:text1.text];
    [array addObject:text2.text];
    [array writeToFile:[self dataFilePath] atomically:YES];
    }

    -(IBAction)loadFromFile
    {
    NSString *filePath=[self dataFilePath];
    if ([[NSFileManager defaultManager] fileExistsAtPath:filePath])
    {
    NSArray *array=[[NSArray alloc] initWithContentsOfFile:filePath];
    text1.text=[array objectAtIndex:0];
    text2.text=[array objectAtIndex:1];
    }
    UIApplication *app=[UIApplication sharedApplication];//为关闭做准备
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillResignActive:) name:UIApplicationWillResignActiveNotification object:app];
    }



    程序打开时读取,程序退到后台时写入

    - (void)viewDidLoad
    {
    [super viewDidLoad];

    [self loadFromFile];
    }

    -(void) applicationWillResignActive:(NSNotification *)notification //在viewController中
    {
    [self saveToFile];
    }




  • 相关阅读:
    Flask学习目录
    Android笔记
    PyQt学习目录
    学习目录
    Python学习目录一
    sqlserver STUFF & STR
    PowerShell+Jenkins,实现项目的自动化部署
    DotNet Core Backend development
    .Net Core 类注入单元测试
    团队项目之团队展示&选题
  • 原文地址:https://www.cnblogs.com/phoenix13suns/p/2344138.html
Copyright © 2011-2022 走看看