2

I used codes below to open a file

    NSOpenPanel * panel = [NSOpenPanel openPanel];
            [panel setCanSelectHiddenExtension:YES];
            [panel setRequiredFileType:@"scpt"];
            [panel setAllowsOtherFileTypes:NO];

            [panel
             beginSheetForDirectory:nil
             file:@"Script"
             modalForWindow:[self window]
             modalDelegate:self
             didEndSelector:@selector (openFileDidEnd:returnCode:contextInfo:)
             contextInfo:nil];

-(void)openFileDidEnd:(NSSavePanel*)panel returnCode:(int)returnCode contextInfo:(void*)contextInfo
{


if(returnCode == NSOKButton)
{

    NSString *s=[[panel URL] absoluteString];
    [NSThread detachNewThreadSelector:@selector(setFileString:) toTarget:self withObject:s ];

}
};

s value is 'file://home/Users/myName/Desktop/1.scpt'

if I call

bool b=[[NSFileManager defaultManager] fileExistsAtPath:@"file://home/Users/myName/Desktop/1.scpt"];

check if the file with path s exists, it always returns 0

but if I checked in Finder, I found its path is '/Users/myName/Desktop/1.scpt'

bool b=[[NSFileManager defaultManager] fileExistsAtPath:@"/Users/myName/Desktop/1.scpt"];

will return YES!

How can I get the correct string path from url of NSOpenPanel ?

Welcome any comment

monsabre
  • 2,099
  • 3
  • 29
  • 48

1 Answers1

5
NSString *s=[[panel URL] absoluteString];

should be

NSString *s=[[panel URL] path];

If you're targeting Snow Leopard or later I recommend using

- (void)beginSheetModalForWindow:(NSWindow *)window completionHandler:(void (^)(NSInteger result))handler

as the method you're using is deprecated, and using blocks is much easier.

Francis McGrew
  • 7,264
  • 1
  • 33
  • 30
  • To clarify the problem, a URL responds to `absoluteString` with a string representation of the URL. That's not a pathname and can't be used with methods like `fileExistsAtPath:` that need one. To get the URL's pathname, you need to ask it for its `path`. – Peter Hosey Oct 23 '11 at 16:03