• 获取文件的路径,即获取documents的路径


    1. NSSearchPathForDirectoriesInDomains和NSHomeDirectory
    iPhone和symbian 3rd一样,会为每一个应用程序生成一个私有目录,这个目录位于/Users/sundfsun2009/Library/Application Support/iPhone Simulator/User/Applications下,并随即生成一个数字字母串作为目录名,在每一次应用程序启动时,这个字母数字串都是不同于上一次。

    通常使用Documents目录进行数据持久化的保存,而这个Documents目录可以通过 NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserdomainMask,YES) 得到,代码如下:

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];

    // NSString *path = [documentsDirectory stringByAppendingPathComponent:@"aa.plist"];

    NSLog(@"path: %@",path);

    打印结果如下:

    path: /Users/apple/Library/Application Support/iPhone Simulator/4.3/Applications/550AF26D-174B-42E6-881B-B7499FAA32B7/Documents

    而这个目录还可以通过 NSHomeDirectory()来得到,代码如下:

    NSString *destPath = NSHomeDirectory();
    NSLog(@"path: %@",destPath);
    //destPath = [destPath stringByAppendingPathComponent: @"Documents"];
    //NSString *xmlpath = [destPath stringByAppendingPathComponent: @"menu/menu.xml"];

    打印结果如下:

    path: /Users/apple/Library/Application Support/iPhone Simulator/4.2/Applications/6F4BC466-C5D6-440C-BAAC-BE20FA468C61

    看看两者打印出来的结果,我们可以看出这两种方法的不同。

    在documents的路径下创建文件。

    首先要获取documents的路径,如上第6条。

    其次就是下面的语句了:

    NSString *writePath=[NSString stringWithFormat:@"%@/%@.txt",documentsPath,@"aaa"];
    NSData *data = [@"" dataUsingEncoding:NSUTF8StringEncoding];//新文件的初始数据,设为空
    [[NSFileManager defaultManager] createFileAtPath:writePath contents:data attributes:nil];//创建文件的命令在这里

    这样就可以在documents文件夹下创建一个aaa.txt的文件了。哈哈哈哈哈。

    或者是用下面的语句,

    NSString *writePath=[NSString stringWithFormat:@"%@/%@.txt",documentsDirectory,@"bbb"];
    NSError *error;
    [@"fasdfasdasddaa" writeToFile:writePath atomically:YES encoding:NSUTF8StringEncoding error:&error];

    这样就可以在documents文件夹下创建一个bbb.txt的文件了。并且,文件中的有"fasdfasdasddaa"字符。

    总结起来就是,先给要存储的东西取一个名字,然后,找到它的路径。然后以这个名字创建。创建的时候可以添加内容

  • 相关阅读:
    C++常变量
    C++变量(C++变量定义、变量赋值、命名规则)
    463. Island Perimeter
    500. Keyboard Row
    811. Subdomain Visit Count
    901. Online Stock Span
    419. Battleships in a Board
    620. Not Boring Movies
    893. Groups of Special-Equivalent Strings
    575. Distribute Candies
  • 原文地址:https://www.cnblogs.com/gaoxiao228/p/2483542.html
Copyright © 2020-2023  润新知