这是与块相关的内存管理的一个小问题,我不确定何时/在何处发布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)处发布是可以的(没有泄漏),但是这真的是做事情的标准方式吗?(释放同一个对象调用的块中的对象?)。我觉得这里有些奇怪。
At (2),也可以,但只因为访问器块是同步调用的。
为了学习目的..。如果访问器块将被异步调用,该怎么办?在这种情况下,我是否需要使NSFileCoordinator成为ivar,或者作为第一种方法,这样做还好吗?
任何帮助都是非常感谢的。
:)
发布于 2011-11-07 11:38:00
对于给定的代码,我将在(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中的一个类别。
https://stackoverflow.com/questions/8034961
复制相似问题