11

I am trying to copy files that I add to a folder called "includes" to a folder on documents directory called also "includes".

I get a nil value for resContents. Why?

- (void)copyResources{

    NSString *sourcePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"includes"];
    NSString *destPath = [[self applicationDocumentsDirectory] stringByAppendingPathComponent:@"includes"];

    NSArray* resContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:sourcePath error:NULL];

    for (NSString* obj in resContents){
        NSError* error;
        if (![[NSFileManager defaultManager] copyItemAtPath:[sourcePath stringByAppendingPathComponent:obj] toPath:[destPath stringByAppendingPathComponent:obj] error:&error]) {
            NSLog(@"Error: %@", error);;
        }
    }
}
pkamb
  • 33,281
  • 23
  • 160
  • 191
Jaume
  • 913
  • 2
  • 17
  • 31

2 Answers2

6

Your Xcode project should add your includes folder as a Folder Reference and not as a Group.

Groups are just meant to keep things organized rather than provide a folder structure and therefore when copying to the device, all the files end up at the same level.

pkamb
  • 33,281
  • 23
  • 160
  • 191
Ignacio Inglese
  • 2,605
  • 16
  • 18
2

Look into your compiled application bundle.

Usually, the Xcode generated bundles are flat. This means although your added resource files will be copied to the bundle, any directories you created will not and hence there is no "includes" directory at the resource path. Consequently, your source contents will be nil.

So in your case, try using just:

NSString *sourcePath = [[NSBundle mainBundle] resourcePath];

Edit: Well and obviously adding a folder reference also works (credits to Ignacio Inglese).

pkamb
  • 33,281
  • 23
  • 160
  • 191
cli_hlt
  • 7,072
  • 2
  • 26
  • 22
  • ok, but are listed all files, including .nib and plists! I need to select only files from a specific folder. Not possible? – Jaume Feb 10 '12 at 15:37
  • It's a flat structure in the bundle. – twilson Feb 10 '12 at 15:40
  • @Jaume Well then you will have to select the files you need (possibly by a common extension, or keep a list of the filenames in your code). – cli_hlt Feb 10 '12 at 15:48