objective-c-blocks - 如何正确构造对 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
- 我想获得替换文件的授权,所以首先声明我想要的 Auth 请求的类型。
- 然后,内联声明完成处理程序的名称。
- 使用完成处理程序“块”,您请求授权,这会导致操作系统发出一个面板来请求用户的密码 - 您看不到。用户可能需要一段时间才能执行此操作,因此需要完成例程。
- 当完成例程完成时,您可以向您的代码发布完成发生的通知,然后您可以继续执行该文件替换或不替换,具体取决于用户是否允许。
我希望这会有所帮助,当我最初问这个问题时,我真的不熟悉块、完成例程和文件管理器,我花了一段时间才弄明白。我重新发布了带有答案的问题,希望对其他人有所帮助。
解决方案
代码的结构通常类似于
[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;
可以创建强大的参考循环。请参阅在捕获自我时避免强引用循环
推荐阅读
- javascript - 如何在 JS 中“重置”整个脚本?
- database - IBM DB2 PIVOT 一个完整的日期表
- javascript - 如何在javascript中将标题/键添加到多个对象的数组中?
- java - Spring Boot 相当于 Dropwizard 命令?
- java - 将枚举转换为字符串时的奇怪行为
- sqlite - 按第一个非空列排序 sql 查询结果
- reactjs - image 和 h4 元素在 React Material UI 中没有并排出现
- php - 用 PHP 替换 xml 标签内的文本
- python - python3中的异常处理
- plot - Prometheus:如何创建一个时间图,每 0.5 秒绘制一次仪表值,同时保持刮擦间隔为 10 秒