gpt4 book ai didi

cocoa - 检查 NSOpenPanel 是否返回目录

转载 作者:行者123 更新时间:2023-12-03 17:52:50 25 4
gpt4 key购买 nike

尝试确定 NSOpenPanel 是否已返回文件或目录

我使用了 Apple 的 fileExistsAtPath: 示例代码,它对于 fontPath 效果很好但似乎不适用于 openpanel不确定我从 NSURL 获取 NSString 是否正确 - 我仍然是 Cocoa 新手

它确实表明存在语义问题 将“const BOOL *”(又名“constsigned char *”)发送到“BOOL *”类型的参数(又名“signed char *”)会丢弃限定符

请帮忙

- (IBAction)openImage: (id)sender
{
// present open panel...

NSString * extensions = @"tiff/tif/TIFF/TIF/jpg/jpeg/JPG/JPEG/CR2";
NSArray * types = [extensions pathComponents];
NSFileManager *fileManager = [[NSFileManager alloc] init];

//===================================
// example just to see if it works!!
NSArray *subpaths;
BOOL isDir;
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSLibraryDirectory, NSUserDomainMask, YES);
if ([paths count] == 1) {
NSString *fontPath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"Fonts"];
if ([fileManager fileExistsAtPath:fontPath isDirectory:&isDir] && isDir) {
NSLog(@"======= fontPath = %@", fontPath);
}
}
//============================================

// Let the user choose an output file, then start the process of writing samples
NSOpenPanel *openPanel = [NSOpenPanel openPanel];
[openPanel setAllowedFileTypes:types];
[openPanel setCanSelectHiddenExtension:YES];
[openPanel setCanChooseDirectories:YES];
[openPanel beginSheetModalForWindow:_window completionHandler:^(NSInteger result) {
if (result == NSFileHandlingPanelOKButton)
{
// user did select an image...

NSLog(@"URL = %@",[openPanel URL]);
NSString *workFile = [[openPanel URL] absoluteString];
NSLog(@"workFile %@",workFile);
if ([fileManager fileExistsAtPath:workFile isDirectory:&isDir] && isDir) {
NSLog(@"======== It's a dir=======");
}


[self openImageURL: [openPanel URL]];
}
}];
}

最佳答案

当 block 引用在 block 本身外部声明的局部(堆栈)变量时:

  • 将与局部变量具有相同类型和名称的常量添加到 block 中;和

  • 该局部变量的当前用作 block 常量的值

这就是为什么您会收到有关 const BOOL 的错误。当您尝试传递 block 常量 isDir 的地址时其中需要一个非常量的地址。

您可以通过isDir使用__block作为变量添加到 block 中其声明中包含限定符,这意味着使用 isDir block 内引用与 block 外声明的变量完全相同

但是从您的评论来看,这似乎也不是您所需要的,而是您只需要一个 block 本地变量在方法调用中使用和 if陈述。为此,只需在 block 内声明一个变量即可。您已经声明 NSString *workFile在 block 内,只需以相同的方式声明一个本地 bool 值即可。

HTH

关于cocoa - 检查 NSOpenPanel 是否返回目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20999525/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com