Getting iPhone Documents Directory. Is NSSearchPathForDirectoriesInDomains still the only way?

后端 未结 3 1052
星月不相逢
星月不相逢 2021-02-04 13:46

Is the NSSearchPathForDirectoriesInDomains function still the best way to get the path of the iPhone Documents directory? I ask because most topics I see on this are d

相关标签:
3条回答
  • 2021-02-04 14:24

    The current Core Data iOS app template in Xcode provides this method:

    // Returns the URL to the application's Documents directory.
    - (NSURL *)applicationDocumentsDirectory
    {
        return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
    }
    
    0 讨论(0)
  • 2021-02-04 14:28

    This works for me, pretty short and sweet

       #define kDOCSFOLDER [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]
    

    Cheers!

    0 讨论(0)
  • 2021-02-04 14:42

    The Core Data-based application template in Xcode provides this method:

    - (NSString *)applicationDocumentsDirectory {
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
    return basePath;
    }
    

    So it would seem that Apple continues to endorse getting the documents directory that way. You could put it into a category, I suppose, but I have found it is enough to include that method in the small handful of classes in a given app that need to do work in the documents directory. If you're doing a lot of file stuff all over the place, you might consider refactoring your code a bit to confine those tasks to one or two manager classes.

    For me, at least, the third or fourth time I said "Hey, getting the docs directory is a pain in the neck" was the point where I realized some opportunities to shift the file juggling into a dedicated class.

    0 讨论(0)
提交回复
热议问题