首页 > 解决方案 > 如何正确构造对 requestAuthorizationOfType: 的方法调用,NSWorkspace 方法?

问题描述

我要重新提问,然后清楚地回答这个我认为被不当删除的问题。这个问题涉及我第一次尝试正确构建对 NSAuthorization 和 NSFileManager 的调用,并且涉及的块在我看来非常类似于 Objective-C,描述不佳,并且几乎没有代码示例。所以,这就是答案。

[self set_theWorkspace:[NSWorkspace sharedWorkspace]];
theType = NSWorkspaceAuthorizationTypeReplaceFile;

void (^myCompletionHandler)(NSWorkspaceAuthorization *, NSError *); // declare the completion routine

myCompletionHandler = ^(NSWorkspaceAuthorization *theAuth, NSError *theError) { // perform the auth request
    if (theError == nil) {
        [self set_theFileAuthorization:theAuth]; // save the authorization
        [(NSNotificationCenter*)[NSNotificationCenter defaultCenter] postNotificationName:@"myCompletionHandlerDidComplete" object:nil]; // let your code know the handler completed
    }
};

[theWorkspace requestAuthorizationOfType:theType completionHandler:(void (^)(NSWorkspaceAuthorization *theAuth, NSError *theError))myCompletionHandler]; // execute the request
  1. 我想获得替换文件的授权,所以首先声明我想要的 Auth 请求的类型。
  2. 然后,内联声明完成处理程序的名称。
  3. 使用完成处理程序“块”,您请求授权,这会导致操作系统发出一个面板来请求用户的密码 - 您看不到。用户可能需要一段时间才能执行此操作,因此需要完成例程。
  4. 当完成例程完成时,您可以向您的代码发布完成发生的通知,然后您可以继续执行该文件替换或不替换,具体取决于用户是否允许。

我希望这会有所帮助,当我最初问这个问题时,我真的不熟悉块、完成例程和文件管理器,我花了一段时间才弄明白。我重新发布了带有答案的问题,希望对其他人有所帮助。

标签: objective-c-blocks

解决方案


代码的结构通常类似于

[NSWorkspace.sharedWorkspace requestAuthorizationOfType:NSWorkspaceAuthorizationTypeReplaceFile
        completionHandler:^(NSWorkspaceAuthorization *theAuth, NSError *theError) {
    if (theError == nil) {
        self.theFileAuthorization = theAuth; // save the authorization
        [NSNotificationCenter.defaultCenter postNotificationName:@"myCompletionHandlerDidComplete" object:nil]; // let your code know the handler completed
    }
};

解释:

[self set_theWorkspace:[NSWorkspace sharedWorkspace]];

Camel case 用于包含多个单词的名称,set_theWorkspace:应命名为setTheWorkspace:。在现代 Objective-C 中使用点语法:self.theWorkspace = NSWorkspace.sharedWorkspace;. 每个应用程序有一个共享NSWorkspace对象,并且[NSWorkspace sharedWorkspace]总是返回相同的NSWorkspace,除非经常使用,否则无需存储它。

[(NSNotificationCenter*)[NSNotificationCenter defaultCenter] postNotificationName:@"myCompletionHandlerDidComplete" object:nil]; // let your code know the handler completed

[NSNotificationCenter defaultCenter]返回 a NSNotificationCenter,无需类型转换。

警告:

self.theFileAuthorization = theAuth;

可以创建强大的参考循环。请参阅在捕获自我时避免强引用循环


推荐阅读