NSDocumentDirectory

Discussion in 'iOS Programming' started by larswik, Sep 11, 2011.

  1. larswik macrumors 68000

    Joined:
    Sep 8, 2006
    #1
    I read the doc's tonight on NSDocumentDirectory and they had this example bellow. I am confused as to why it is creating an NSArray? the instance variable is 'paths' and looking at other material when you define paths you use NSStrings.

    The next line does create an NSString pointer which points to the first index of the paths array, why an array? Is it not a normal file directory? Must everything be stored in an array before it can be stored in the NSDocumentDirectory?

    Code:
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    
    NSString *documentsDirectory = [paths objectAtIndex:0];
     
  2. jiminaus macrumors 65816

    jiminaus

    Joined:
    Dec 16, 2010
    Location:
    Sydney
    #2
    NSSearchPathForDirectoriesInDomains can return multiple paths. In this code, you're just arbitrarily taking just the first path returned.
     
  3. admanimal macrumors 68040

    Joined:
    Apr 22, 2005
    #3
    You have to consider how you are obtaining NSDocumentsDirectory. Specifically, you are using the utility function NSSearchPathForDirectoriesInDomains, which under some circumstances (i.e. when you ask it for a particular type of directory and/or domain) can effectively return more than one thing. Obviously, returning more than one thing requires it to have a return type of NSArray (or some kind of collection), so whether you request something that should return one thing or 10 things, it has to return an NSArray.
     
  4. PhoneyDeveloper macrumors 68030

    PhoneyDeveloper

    Joined:
    Sep 2, 2008
    #4
    On iOS it will only ever return a single value in the array (unless something changes). On MacOS X it can return multiple values.

    You can easily write your own wrapper function that simply returns the single path as a string. This will make your code a little neater.
     
  5. larswik thread starter macrumors 68000

    Joined:
    Sep 8, 2006
    #5
    I'm getting it. I thought by reading the doc's that I would be writing NSArrays to the directory. But it sounds like if I want to store 10 jpg images in a folder on the iPhone NSDocumentDirectory downloaded from the web, I can do this. But when I want to retrieve the images I need to load them in to an NSArray. But I am assuing you can store NSDictionayrs or NSArrays in the NSDocumentsDirectory too.

    Thanks!
     
  6. jiminaus macrumors 65816

    jiminaus

    Joined:
    Dec 16, 2010
    Location:
    Sydney
    #6
    Either you're grossly confused, or this post is grossly confusing.

    You cannot store NSArray, NSDictionary, or any kind of objects in NSDocumentsDirectory. NSDocumentDirectory is just a constant defined in NSPathUtilities.h.

    If you mean that actual documents directory in the iOS file-system, this is just a container for files and other (sub-)directories. You cannot store objects in a file-system directory. You can archive objects into a file in a directory. You can enumerate over the files and subdirectories of a directory using the likes of NSFileManager.

    How you load 10 jpegs in the document directory depends on what technique you're using to load them. This has nothing to do with the fact the NSSearchPathForDirectoriesInDomains returns an NSArray.
     
  7. larswik thread starter macrumors 68000

    Joined:
    Sep 8, 2006
    #7
    Jim, Sorry that was a dumb question. I understand that I can not store NSArrays and so on in a directory. Just like on my Mac I can not store those items. But I can store them in a plist file which I can store on the drive.

    But if I do understand it right, also from what you said, I can store sound files, images, textfiles in the directory for my app on an iPhone because it is a directory kind of like a Mac OSX directory?

    Thanks again Jim
     
  8. jiminaus macrumors 65816

    jiminaus

    Joined:
    Dec 16, 2010
    Location:
    Sydney
    #8
    Yes. The documents directory in iOS is free for you to use as you will. It's also inside your app's sandbox, so you there won't be anything in it except that your app put in there. For example, other apps have other documents directories in their own sandboxes.
     
  9. larswik thread starter macrumors 68000

    Joined:
    Sep 8, 2006
    #9
    Thanks Jim, I was playing with it tonight and I got it to write to the directory just fine. I was able to read the file back in to test, but instead of the label text field displaying the contents of the text file, it is displaying the path to the file. NSString * theNames I thought would contain the contents of the file?
    The code
    Code:
    - (IBAction)pushButton:(id)sender {
        NSFileManager *filemgr = [NSFileManager defaultManager];
        
        NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES); // create path to theDirectory
        NSString *documentsDirectory = [paths objectAtIndex:0];
        
        NSLog(@"Documents directory: %@",[filemgr contentsOfDirectoryAtPath:documentsDirectory error:nil]); //writes out what is in directory
        
        NSString *pathToNames = [documentsDirectory stringByAppendingPathComponent:@"nameTests.txt"]; //looks for this file in the Directory
        NSString *theNames = [[NSString alloc] initWithContentsOfFile: pathToNames encoding: NSUTF8StringEncoding error: nil];
        
        NSLog(@"TheNames: %@", theNames); // writes out the string
    
        lableTextField.text = theNames; //the text lable displays the result
        [theNames release];
    }
    
     
  10. admanimal macrumors 68040

    Joined:
    Apr 22, 2005
  11. larswik thread starter macrumors 68000

    Joined:
    Sep 8, 2006
    #11
    In Xcode I went to File/New and created an Empty file and saved it as nameTests.txt. This file was then saved in my project folder. I also included it for you to see. But what is in the file is just 3 lines of text.

    Casa Blanca
    Fishouse
    Boathouse
     

    Attached Files:

  12. jiminaus macrumors 65816

    jiminaus

    Joined:
    Dec 16, 2010
    Location:
    Sydney
    #12
    This code works for me when connected to a "Read File" button. Although I created the file on the device (via a Create File button). But even if the file doesn't exist, I don't get the file name, I just get theName being nil.
     
  13. larswik thread starter macrumors 68000

    Joined:
    Sep 8, 2006
    #13
    That is weird. I must be doing something else wrong if it is working for you. Here is the project I compressed down. It must be something simple since it is displaying the path to the file and not the contents of the file.

    Thanks
     

    Attached Files:

  14. admanimal macrumors 68040

    Joined:
    Apr 22, 2005
    #14
    The problem is exactly what I figured it would be. Your writeToFile method, which I assume was meant to copy the nameTests.txt file from the app bundle to the documents directory, does not do that. Instead, it creates a new file called nameTests.txt whose contents is its own path (i.e. exactly what you see being printed out to the console).
     
  15. larswik thread starter macrumors 68000

    Joined:
    Sep 8, 2006
    #15
    Ahhh. So the problem is not reading the file from the directory on the iphone but the way that it is written to the directory. In this case I never wrote the text file correctly.

    Let me break my method writeToFile down so I can learn what I am doing wrong. I deleted some of the code from the the method like NSLogs so I can just show the core components.
    Code:
    -(void)writeToFile{
        NSString *documentsDirectory = [NSHomeDirectory()  stringByAppendingPathComponent:@"Documents"]; // Point to Document directory
    The code above creates an NSString pointer that stores the path to Documents directory on my iPhone.
    Code:
        NSString *fileSavePath = [@"~/Documents/programming/iphoneNSDirect/iphoneNSDirect/nameTests.txt" stringByExpandingTildeInPath];
    The code above I create a NSString pointer called fileSavePath which points to the file in my computer.
    Code:
    NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"nameTests.txt"];
    The code above is what I suspect is my problem area. I thought it was creating a pointer called filePath which assigns the documentDirectory as the path and saves the file named nameTests.txt to that location.
    Code:
    [fileSavePath writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
    }
    The code above handles the actual writing of the file to the directory on the iPhone.
     
  16. admanimal macrumors 68040

    Joined:
    Apr 22, 2005
    #16
    Let's slow down a second here, because it seems you are missing a key step in this whole process.

    Am I correct in thinking that you are trying to take the nameTests.txt file that you included in your project (the same one you attached in this thread earlier), and copy it to an identical file in your application's Documents directory?
     
  17. larswik thread starter macrumors 68000

    Joined:
    Sep 8, 2006
  18. admanimal macrumors 68040

    Joined:
    Apr 22, 2005
    #18
    OK, so the first thing you should notice is that at no point do you reference the existing file that you want to copy. That file is located in the application bundle, whose path you can get by doing this:

    Code:
    NSString *bundleTextPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"nameLists.txt"];
    
    It looks like you might have mistakenly thought that the path of this file would be the same as the path of the file on your desktop file system (i.e. fileSavePath). In any case, your filePath NSString does appear to contain the correct path in the app's Documents directory where I assume you want the file to end up. So now the question is how do we get it there. You can either use the copyItemAtPath method of NSFileManager, or to follow a bit closer to your original code, read the file at bundleTextPath into an NSString, and then write it back out to filePath.

    I will tell you that this:
    Code:
    [bundleTextPath writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
    
    will not work, because you would be writing a file's path to another file, and not a file to another file. That is, NSString has no idea that bundleTextPath is actually a path to a text file, so it's not going to open that file and then write it out to filePath. You have to use some other NSString method to get the contents of bundleTextPath into an NSString first, then use writeToFile on that string.
     
  19. larswik thread starter macrumors 68000

    Joined:
    Sep 8, 2006
    #19
    Huh, when you write that I am baffled that I missed the whole linking to my file in my computer in the Bundle.

    You have given me lots of food for thought and thank you for giving me a push and not giving me the answer to this directly. My goal tonight is to try to fill in the blanks to make this work. That way I learn it!

    The over all goal is to have a file on my server to be downloaded 1 time a day. Then from the list of clients in the txt document I would create a UITable. This way I can add and remove clients by just changing the list.

    Thank you again!
     
  20. larswik thread starter macrumors 68000

    Joined:
    Sep 8, 2006
    #20
    I went back to the beginning and was trying again tonight to get this. I used NSLog to display the paths and wanted to check to see if the NSBundle MainBundle is right? But the NSLog result seems to be on the iPhone and not the project folder on my Mac if I am reading it right?

    Is that correct? or should the NSBundle MainBundle be something like /Users/larspro/Documents/programming/iphoneNSDirect/iphoneNSDirect/nameTests.txt or should it start with var/mobile/Applications/.......

    Here is the code so far
    Code:
    -(void)writeToFile{
        NSFileManager *fileManager = [NSFileManager defaultManager];
        
        NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSLog(@"paths: %@", paths); //path to Documents in iphone
        
        NSString *resourceForFile = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"nameTests.txt"];
        NSLog(@"main Bundle: %@", resourceForFile); //path to Documents in iphone
    
    }
    
     
  21. admanimal macrumors 68040

    Joined:
    Apr 22, 2005
    #21
    The path that you are seeing is correct. While nameTests.txt might exist in /Users/larspro/Documents/programming/iphoneNSDirect/iphoneNSDirect/, when you actually build the app it is copied inside of the app bundle, and that is where you should be accessing it from (and of course on a device you would have no choice) in order to copy it into the Documents directory.
     
  22. jnoxx macrumors 65816

    jnoxx

    Joined:
    Dec 29, 2010
    Location:
    Aartselaar // Antwerp // Belgium
    #22
    What I did, is add a Copy Build Phase to my Target, create a seperate folder there, with loads of images, and loop through that Directory in my code.
    Maybe that is a bit more your aim?
     
  23. larswik thread starter macrumors 68000

    Joined:
    Sep 8, 2006
    #23
    I don't know why this is giving me so much grief trying to understand this read write concept to the ios.

    The next line of code I added was to just copy over the file with an NSFileManager that you made mention to admanimal. I then found online an Enumerator to list what is in the directory. I created a new txt file and tried to copy that in so I should have 2 files in there. but when the enumerator runs it only sees the 1 file still. So it is still not correct.

    Code:
    -(void)writeToFile{
        NSFileManager *fileManager = [NSFileManager defaultManager];
        
        NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSLog(@"paths: %@", paths); //path to Documents in iphone
        
        NSString *resourceForFile = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"nameTestsTwo.txt"];
        NSLog(@"main Bundle: %@", resourceForFile); //path to Documents in iphoneerror:nil];
        
        [fileManager copyItemAtPath:resourceForFile toPath:documentsDirectory error:nil];
        
        NSFileManager *manager = [NSFileManager defaultManager];
        NSDirectoryEnumerator *direnum = [manager enumeratorAtPath:documentsDirectory];
        
        NSString *filename;
        
        while ((filename = [direnum nextObject] )) {
            NSLog(@"Item: %@",filename);
                
        }
    }
     
  24. PhoneyDeveloper macrumors 68030

    PhoneyDeveloper

    Joined:
    Sep 2, 2008
    #24
    When you use copyItemAtPath:toPath:error: the path parameters must include the file name. You can't just specify a directory where you want the toPath to go. Also, it's a good idea to check the value that's returned and the error parameter for help to figure out if/why it's not working.
     
  25. larswik thread starter macrumors 68000

    Joined:
    Sep 8, 2006
    #25
    I will try that. I went through and read the doc's again after reading your post for that method. The description does mention that I need the title as well. So when you write a file you need to tell it what it is and when you copy a file you need to do the same thing. The doc's also said to make sure nothing exists at the destination path that already has that name. The must also be an over write method as well.

    I don't know why I am struggling with this so much with this concept.

    Thanks
     

Share This Page