2011-12-03 4 views
1

私のメインバンドルのファイルを、以下のコードでファイル名でDocumentsディレクトリにコピーできますが、ワイルドカードに基づいてどのようにコピーできますか?たとえば、myimageX.jpgという名前のファイルがいくつかあります(xは乱数を表します)。メインバンドルに含まれているすべてのものをループして、ドキュメントに存在しない場合はコピーします。メインバンドルからワイルドカードファイル名をドキュメントにコピーしますか?

BOOL success; 
NSFileManager *fileManager = [NSFileManager defaultManager]; 

myfileName = @"myimage322.jpg"; 
documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES); 
documentsDir = [documentPaths objectAtIndex:0]; 
filePath = [documentsDir stringByAppendingPathComponent:myfileName]; 

success = [fileManager fileExistsAtPath:filePath]; 
if(success) return; 
NSString *filePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:myfileName]; 
[fileManager copyItemAtPath:filePathFromApp toPath:filePath error:nil]; 

[fileManager release]; 

答えて

2

メソッドfileExistsAtPathが役立ちます。最初にバンドルの内容を列挙し、同じファイル(同じファイル名の)がドキュメントに存在するかどうかをチェックします。ここで

はそれを行う方法です:

NSString *docsDir = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]; 
NSString *bundleDir = [[NSBundle mainBundle] resourcePath]; 

NSFileManager *localFileManager=[[NSFileManager alloc] init]; 
NSDirectoryEnumerator *dirEnum = [localFileManager enumeratorAtPath:bundleDir]; 

NSString *file; 

while (file = [dirEnum nextObject]) { 

    if (![[NSFileManager defaultManager] fileExistsAtPath: [docsDir stringByAppendingPathComponent:file]]) { 

     [[NSFileManager defaultManager] copyItemAtPath:[bundleDir stringByAppendingPathComponent:file] 
               toPath:[docsDir stringByAppendingPathComponent:file] error:nil];   
    } 

} 

[localFileManager release]; 

これは、ここで見つけることができNSFileManagerクラスの参照からのコードの修正版である:これは素晴らしいですが、ファイルのトンがある http://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSFileManager_Class/Reference/Reference.html

+0

このバンドルでは、私は非常に頻繁にそれらのすべてを通してループを持つことを嫌いになるでしょう。 Xcodeで作成された特定のグループ内のファイルのみをループする方法はありますか? – user973984

+0

指定したフォルダの内容を列挙できます。フォルダを作成し、「追加されたフォルダのフォルダ参照を作成する」チェックボックスをオンにして追加します。次に、そのフォルダの内容をループすることができます - リソースフォルダ全体ではありません。 – RaffAl

関連する問題