0

NSFileManagerを使用して、MyApp.app/Documentフォルダーにファイルを含むフォルダーを作成したいと思います。(MyAppは私のカスタムアプリです。)

そこで、IMG_0525.jpg(テスト用)をプロジェクトのフォルダにコピーしました。

次に、プロジェクトのフォルダーからMyApp.app/Documentフォルダーにコピーしようとします。

しかし、パス名を指定する方法がわかりません。(送信元と宛先のパス)

方法を教えていただけますか?

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    [self generateTableContents];

}


- (void)generateTableContents {

    NSFileManager * fileManager = [NSFileManager defaultManager];
    NSArray *appsDirectory = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentPath = [appsDirectory objectAtIndex:0];
    NSLog(@"documentPath : %@", documentPath);

    [fileManager changeCurrentDirectoryPath:documentPath];
    [fileManager createDirectoryAtPath:@"user_List1" withIntermediateDirectories:YES attributes:nil error:nil];

    // I'm trying to copy IMG_0525.jpg to MyApp.app/Document/user_List1 folder.
    [fileManager copyItemAtPath:<#(NSString *)srcPath#> toPath:<#(NSString *)dstPath#> error:<#(NSError * *)error#>];


}

ここに画像の説明を入力してください

4

1 に答える 1

1
  • このドキュメント ディレクトリを取得するためのコードNSSearchPathForDirectoriesInDomainsは正しいですが、これは「MyApp.app/Documents」を指していないことに注意してください。実際、実行時にアプリケーションのバンドル コンテンツを変更することはできません (ただし、変更するとバンドルのコード署名に違反します)。ただし、アプリケーションのサンドボックス ("MyApp.app.app " bundle) であり、これがこのアプリケーションのサンドボックスの Document フォルダーへのパスであり、呼び出しNSSearchPathForDirectoriesInDomainsによって返されます

  • そうは言っても、ファイルの宛先フォルダーができたので、それがメソッドのtoPath:パラメーターです-copyItemAtPath:toPath:error:。唯一欠落している部分は、バンドル内のリソースを指すソース パスです (バンドル内でコンパイルされた後に、Xcode プロジェクトに追加した画像ファイルを指すため)。

このソース パスを取得するには、-[NSBundle pathForResource:ofType:]メソッドを使用します。これは非常に簡単に使用できます。

NSString* sourcePath = [[NSBundle mainBundle] pathForResource:@"IMG_0525" ofType:"jpg"];
  • メソッドが失敗した場合にエラーを取得する場合は、最後のerror:パラメーターを にするNULLか、オブジェクトへのポインターにすることができます。そのパラメーターについては、呼び出しの前に変数を作成し、 のこの 3 番目のパラメーターに渡すだけです。NSError*-copyItemAtPath:toPath:error:NSError* error;&error-copyItemAtPath:toPath:error:

したがって、完全な呼び出しは次のようになります。

NSError* error; // to hold the error details if things go wrong
NSString* sourcePath = [[NSBundle mainBundle] pathForResource:@"IMG_0525" ofType:"jpg"];

BOOL ok = [fileManager copyItemAtPath:sourcePath toPath: documentPath error:&error];
if (ok) {
  NSLog(@"Copy complete!");
} else {
  NSLog(@"Error while trying to copy image to the application's sandbox: %@", error);
}
于 2012-10-03T17:10:13.770 に答える