首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >NSFileCoordinator泄漏

NSFileCoordinator泄漏
EN

Stack Overflow用户
提问于 2011-11-07 10:06:17
回答 1查看 665关注 0票数 3

这是与块相关的内存管理的一个小问题,我不确定何时/在何处发布fc

代码语言:javascript
复制
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)处发布是可以的(没有泄漏),但是这真的是做事情的标准方式吗?(释放同一个对象调用的块中的对象?)。我觉得这里有些奇怪。

At (2),也可以,但只因为访问器块是同步调用的。

为了学习目的..。如果访问器块将被异步调用,该怎么办?在这种情况下,我是否需要使NSFileCoordinator成为ivar,或者作为第一种方法,这样做还好吗?

任何帮助都是非常感谢的。

:)

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-11-07 11:38:00

对于给定的代码,我将在(2)处发布。如果您在(1)处释放,您可以将fc从内部拆下来。在调用块之后,无法知道fc可能需要做什么。

对于异步情况,我使用了类似这样的代码(尽管与NSFileCoordinator不同):

代码语言:javascript
复制
__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中的一个类别。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8034961

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档