我在NSOpenPanel runModalForDirectory:
用較新的beginWithCompletionHandler:
.
結果并不如預期。看起來beginWithCompletionHandler:
不等待用戶完成他或她的選擇!
請讓我知道我做錯了什么,或提出不同的解決方案來替換已棄用的方法。
if ([destpath isEqualToString:@""])
{
long result;
NSOpenPanel *oPanel = [NSOpenPanel openPanel];
[oPanel setAllowsMultipleSelection:NO];
[oPanel setCanChooseDirectories:YES];
[oPanel setCanChooseFiles:NO];
result = [oPanel runModalForDirectory:NSHomeDirectory() file:nil types:nil];
if (result == NSModalResponseOK)
{
destpath = [[oPanel URL] retain].path;
NSLog(@"destpath is : %@", destpath);
}
else
return;
}
NSLog(@"MADE IT HERE!! -- destpath is : %@", destpath);
我將代碼替換為:
if ([destpath isEqualToString:@""])
{
// long result; // FIXED!! Changed int to long
NSOpenPanel *oPanel = [NSOpenPanel openPanel];
[oPanel setAllowsMultipleSelection:NO];
[oPanel setCanChooseDirectories:YES];
[oPanel setCanChooseFiles:NO];
[oPanel beginWithCompletionHandler:^(NSInteger result) {
if(result == NSModalResponseOK) {
destpath = [[oPanel URL] retain].path;
NSLog(@"destpath is : %@", destpath);
}
else
return;
}];
}
NSLog(@"MADE IT HERE!! -- destpath is : %@", destpath);
當我運行原始代碼時,我看到以下 NSLog 訊息:
022-09-04 12:20:18.175924-0400 iRipCD[69097:3332748] destpath is : /Users/grinch/Downloads
2022-09-04 12:20:18.175982-0400 iRipCD[69097:3332748] MADE IT HERE!! -- destpath is : /Users/grinch/Downloads
但是新代碼不起作用。該程式不會等待用戶完成他或她對所需目錄的選擇。我看到以下 NSLog 訊息:
2022-09-04 12:15:30.595589-0400 iRipCD[68991:3329339] MADE IT HERE!! -- destpath is :
2022-09-04 12:15:34.320552-0400 iRipCD[68991:3329339] destpath is : /Users/grinch/Downloads
僅供參考 - destpath 在同一個檔案中更早地被初始化:
- (id)init
{
self = [super init];
task = nil;
timer = nil;
destpath = @"";
taskOutput = [[NSMutableString alloc] init];
fileList = [[NSMutableArray alloc] initWithCapacity:15];
[(id) [NSApp delegate] setMaster:self]; // FIXED THIS!! Added (id)
return self;
}
uj5u.com熱心網友回復:
看起來必須使用一個runModal
來確保 NSOpenPanel 物件等待用戶選擇目錄。
該beginWithCompletionHandler:
方法不等待用戶完成他或她的選擇。
以下代碼似乎有效:
if ([destpath isEqualToString:@""])
{
NSOpenPanel *oPanel = [NSOpenPanel openPanel];
[oPanel setAllowsMultipleSelection:NO];
[oPanel setCanChooseDirectories:YES];
[oPanel setCanChooseFiles:NO];
//
// N.B. -- beginWithCompletionHandler: does not wait for the
// user to finish with his or her selection!
//
//[oPanel beginWithCompletionHandler:^(NSInteger result) {
// if(result == NSModalResponseOK) {
//
// Use runModal to ensure that the program waits for the user
// to finish with his or her selection!
//
if ([oPanel runModal] == NSModalResponseOK)
{
destpath = [[[oPanel URL] path] retain] // Also fixed memory bug!
NSLog(@"destpath is : %@", destpath);
}
else
return;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/506299.html