NSSearchPathForDirectoriesInDomains returns the wrong directory

后端 未结 4 1423
無奈伤痛
無奈伤痛 2021-01-02 03:43

I\'m using NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) to get the application documents directory in my app, but the array t

相关标签:
4条回答
  • 2021-01-02 04:16

    I'm having the exact same issue, and in my case it's because I'm running the code from an XCTest class.

    My guess is that the tests are not run in the application sandbox.

    That's because my tests are related to a static library project, included in the main project.

    As soon as I run the exact same code from a run of my app, the paths are returned correctly.

    Hope this helps.

    0 讨论(0)
  • 2021-01-02 04:19

    Hmm ... so one reason that the directory returned might be different that what you'd expect for an app could be related to the Xcode target type. This wouldn't happen to be a testing target would it? in which case the correct answer could well be an answer w/o an application GUID in it, since in fact it's not an application. This google group discussion implies that if this is the case, you'd be good with simply creating the directory.

    Just for grins, I created the directory /Users/me/Library/Application Support/iPhone Simulator/Documents from the terminal window, and now it appears to run. There are still test errors, but those might be real.

    I'd recommend that you change your test app to create the documents directory if it's missing - something like:

      if(![[NSFileManager defaultManager] createDirectoryAtPath:NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) withIntermediateDirectories:YES attributes:nil error:NULL])
            NSLog(@"Error: Create folder failed %@", NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES));
    
    0 讨论(0)
  • 2021-01-02 04:25

    You can try this:

     /**
     Returns the path to the application's Documents directory.
     */
    - (NSString *)applicationDocumentsDirectory {
    return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    }
    

    I believe you are only missing the lastObject message.

    0 讨论(0)
  • 2021-01-02 04:26

    This works for me:

    [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory
                                            inDomains:NSUserDomainMask] lastObject];
    
    0 讨论(0)
提交回复
热议问题