3

これは、ブロックに関連するメモリ管理に関する些細な質問の 1 つであり、いつどこfcで解放する必要があるのか​​ わかりません

NSFileCoordinator *fc = [[NSFileCoordinator alloc] initWithFilePresenter:nil];
NSError *error = nil;
[fc coordinateWritingItemAtURL:sourceURL
                       options:NSFileCoordinatorWritingForDeleting
                         error:&error
                    byAccessor:^(NSURL *newURL) {

            // if error is not nil this block will not be called
            NSError *anError = nil;
            NSFileManager *fm = [NSFileManager defaultManager];
            [fm removeItemAtURL:newURL error:&anError];
            dispatch_async(q_main, ^{
                // change to the main queue and update the UI
                completion(anError);
        });
        // *** (1) Release here ? ***
        // [fc release];
        }];

// *** (2) or Release here ? ***
// [fc release]

if (error) {
    // change to the main queue and update the UI
    dispatch_async(q_main, ^{
        completion(error);
    });
}

(1)でリリースすればOK(リークなし)だと思いますが、これは本当に標準的なやり方なのでしょうか? (同じオブジェクトが呼び出すブロック内のオブジェクトを解放する??)。ここに何か違和感を感じます。

(2)でもOKですが、アクセサーブロックが同期的に呼び出されるためです。

学習目的で...アクセサーブロックが非同期で呼び出されるとどうなりますか? (NSFileCoordinatorの必要のない架空のケース)そのような場合、ivarを作成fcする必要がありますか、それとも最初のアプローチとしてそれを実行しても問題ありませんか?

どんな助けでも大歓迎です

:)

4

1 に答える 1

2

指定されたコードについては、(2) でリリースします。(1)で離すと下fcから崩れる可能性があります。fcブロックを呼び出した後に何をする必要があるかを知る方法はありません。

非同期の場合、次のようなコードを使用しました (ただし、 は使用しませんNSFileCoordinator)。

__block NSWindowController *wc = [[NSWindowController alloc] initWithWindowNibName:@"foo"];
[NSApp beginSheet:[wc window] modalForWindow:[self window] completionHandler:^(NSInteger returnCode) {
    if(NSOKButton == returnCode) {
      // Do something
    }
    [wc release], wc = nil;
  }];

-beginSheet:modalForWindow:completionHandler:は私が追加したカテゴリですNSApplication

于 2011-11-07T11:38:00.943 に答える