Return filename on label?
I am working on an encryption tool, and I have a file chooser that a user can go into to select a file to encrypt. My problem is fairly easy. After the user clicks the "select" button in the file chooser, the filename must be returned to a label on the application. The problem is that I can't enter the window which holds the select button to connect to the IBAction. How can I return the filename to that label after the user clicks select? Can someone perhaps upload the code that would 开发者_运维技巧do that? I am kind of a noob right now, so please talk in simple terms... Step by step instruction would be greatly appreciated
Thanks so much
The following is the code for the file selector:
- (IBAction)fileChooser:(id)sender {
int i;
NSOpenPanel* openDlg = [NSOpenPanel openPanel];
[openDlg setCanChooseFiles:YES];
[openDlg setCanChooseDirectories:YES];
[openDlg setPrompt:@"Select"];
if ([openDlg runModalForDirectory:nil file:nil] == NSOKButton )
{
NSArray* files = [openDlg filenames];
for( i = 0; i < [files count]; i++ )
{
[files objectAtIndex:i];
}
}
}
“return the filename to that label” doesn't make sense. A function or method returns a value only to the function or method that called it; that is the only thing “return” ever means in C and Objective-C. Moreover, when a function or method returns, it ends. It is no longer running. It returns control of the program to the function or method that called it.
So returning a value from a loop would not make sense here (the method would only process the first filename), and returning a value “to [an object]” makes no sense.
You need to create an outlet to the field (a label is a kind of NSTextField) in the class that implements fileChooser:
, and hook that outlet up in the nib editor. Then you can use that outlet to tell the field to set its stringValue
.
(Important note: Unlike in Cocoa Touch, most AppKit classes do not use formal properties. You will have to send the field a setStringValue:
message.)
Outlets are covered by the Cocoa Fundamentals Guide, and you can find the NSTextField documentation in the AppKit framework reference.
One other thing: Since it is possible and quite reasonable for the user to select multiple files, you should handle that case. Simply setting the text field's string value to each filename in turn will leave it showing only the last filename in the array—not really much different from setting it to the first filename and returning. Once you get the text field working, you should replace it with a table view.
If, on the other hand, you don't want to support multiple files, then (1) why? and (2) consider setting the open panel to disallow multiple selection. (See my answer on your previous question for documentation references in that direction.) Then you can assume that, when the response is “OK”, the filenames array contains exactly one item, and cut out the loop entirely.
精彩评论