簡體   English   中英

Objective-C的代表

[英]Delegates in Objective-C

我正在嘗試在Objective-C中探索一些代碼。 我遇到了一個開源程序-批處理重命名器。 我正在查看其代碼並添加了自己的實現。 這段代碼中有一件事我無法理解-我希望有人能夠幫助我。 問題是有一個重命名器委托“-(void)renamed”,我不知道如何調用它。 因此,我想知道程序如何知道何時調用/使用此委托。 代碼如下:

#import "ControllerMain.h"

static NSString *addFilesIdentifier = @"addFiles_item";
static NSString *removeFilesIdentifier = @"removeFiles_item";
static NSString *cleanAllIdentifier = @"cleanAll_item";
static NSString *updateUrl = @"http://www.hardboiled.it/software/update.xml";


@implementation ControllerMain

- (id)init
{
    self = [super init];
    //init some object
    tableSource = [[NSMutableArray alloc] init];
    updater = [[STUpdateChecker alloc] init];
    renamer = [[STRenamer alloc] init];
    //set some variables
    withExt = NO;//for include the extension in the renaming, default NO
    renamed = NO;//is YES after renaming preview
    insoverappPosition = 0;
    //set the notification for NSControlTextDidChangeNotification
    NSNotificationCenter* nc = [NSNotificationCenter defaultCenter];
    [nc addObserver:self selector:@selector(textDidEndEditing:) name:@"NSControlTextDidChangeNotification" object:nil];
    return self;
}

-(void)awakeFromNib
{
    //set the delegates
    [tabella setDelegate:self];
    [tableSource setDelegate:self];
    [renamer setDelegate:self];
    [updater setDelegate:self];
    //check if the software is updated
    [updater checkUpdateWithUrl:[NSURL URLWithString:updateUrl]];
    //drag' drop - set the dragged types
    [tabella registerForDraggedTypes:[NSArray arrayWithObjects: NSFilenamesPboardType, nil]];

    //toolbar configuration
    toolbar = [[NSToolbar alloc] initWithIdentifier:@"toolbar"];
    [toolbar setDelegate:self];

    //mainWindows properties
    [mainWindow center];
    [mainWindow setTitle:@"macXrenamer"];
    [mainWindow setToolbar:toolbar];

    //set the extension checkbox
    [extSwitch setState:0];

    //Set the custom cell imageAndTextCell
    ImageAndTextCell *imageAndTextCell = nil;
    NSTableColumn *tableColumn = nil;
    tableColumn = [tabella tableColumnWithIdentifier:@"original_name"];
    imageAndTextCell = [[[ImageAndTextCell alloc] init] autorelease];
    [imageAndTextCell setEditable: NO];
    [tableColumn setDataCell:imageAndTextCell];
    //
    //initialize the window for empty table
    [self tableSourceIsEmpty];
    //release the toolbar
    [toolbar release];
}

- (void)dealloc
{
    //release all
    [tabella unregisterDraggedTypes];
    [tableSource release];
    [renamer release];
    [super dealloc];
}

- (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)sender
{
    //close the application
    return YES;
}

/* ###################  tableSource delegates #################################*/
- (void)tableSourceIsEmpty
{
    if (KDEBUG)
        NSLog(@"tablesource is empty");
    [upper_lower setEnabled:NO];
    [from setEditable:NO];
    [to setEditable:NO];
    [insertText setEditable:NO];
    [insertAtPosition setEditable:NO];
    [insertAtPosition setIntValue:0];
    [renameButton setEnabled:NO];
    [annullButton setEnabled:NO];
    [searchField setEditable:NO];
    [replaceField setEditable:NO];
}

- (void)tableSourceIsNotEmpty
{
    if (KDEBUG)
        NSLog(@"tablesource is not empty");
    [upper_lower setEnabled:YES];
    [from setEditable:YES];
    [to setEditable:YES];
    [insertText setEditable:YES];
    [insertAtPosition setEditable:YES];
    [searchField setEditable:YES];
    [replaceField setEditable:YES];
}
-(void)tableSourceDidChange
{
    NSString *countString = [NSString stringWithFormat:@"%d files",[tableSource count]];
    [number_of_files setStringValue:countString];
}
/*####################end tableSource delegates###############################*/

/*######################renamer delegates#####################################*/
- (void)renamed
{
    NSLog(@"renaming preview ok");
    NSTabViewItem *tabItem;
    tabItem = [tabView selectedTabViewItem];
    id tabViewId = [tabItem identifier];

    if ([tabViewId isEqual:@"insert"]) {
        [insertAtPosition setTextColor:[NSColor blackColor]];

    }else if([tabViewId isEqual:@"remove"])
    {
        [from setTextColor:[NSColor blackColor]];
        [to setTextColor:[NSColor blackColor]];
    }
    renamed = YES;
    [renameButton setEnabled:YES];
    [annullButton setEnabled:YES];
}
- (void)notRenamed
{
    renamed = NO;
    NSTabViewItem *tabItem;
    tabItem = [tabView selectedTabViewItem];
    id tabViewId = [tabItem identifier];

    if ([tabViewId isEqual:@"insert"]) {
        [insertAtPosition setTextColor:[NSColor redColor]];

    }else if([tabViewId isEqual:@"remove"])
    {
        [from setTextColor:[NSColor redColor]];
        [to setTextColor:[NSColor redColor]];
    }
    NSLog(@"exception in preview delegate");
    [renameButton setEnabled:NO];
}
/* ###################end renamer delegates ##################################*/

//make the file extension editable
-(IBAction)makeExtEditable:(id)sender
{
    if (KDEBUG)
        NSLog(@"makeExtEditable action");

    if ([sender state] == 0) {
        withExt = NO;
    }else if ([sender state] == 1) {
        withExt = YES;
    }
}

//add files to the table
-(IBAction)addFiles:(id)sender
{
    //start the progression bar
    [progBar startAnimation:self];
    int result;
    NSOpenPanel *oPanel = [NSOpenPanel openPanel];
    [oPanel setCanChooseFiles:YES];
    [oPanel setAllowsMultipleSelection:YES];
    [oPanel setResolvesAliases:NO];
    result = [oPanel runModalForTypes:nil];

    if (result == NSOKButton) {
        NSArray *filesToOpen = [oPanel filenames];
        [tableSource add:filesToOpen];
        [tabella reloadData];
    }
    //stop the progression bar
    [progBar stopAnimation:self];
}

//remove files from the table
-(IBAction)removeFiles:(id)sender
{
    if(KDEBUG)
        NSLog(@"remove the selected file from the table");
    [progBar startAnimation:self];
    NSIndexSet *selected = [tabella selectedRowIndexes];
    [tableSource removeAtIndexes:selected];
    [tabella reloadData];
    [progBar stopAnimation:self];
}

//remove all files from the table
-(IBAction)clearTable:(id)sender
{
    if(KDEBUG)
        NSLog(@"clear all table");
    [progBar startAnimation:self];
    [tableSource cleanAll];
    [tabella reloadData];
    [progBar stopAnimation:self];
}

//annull
-(IBAction)annulRenaming:(id)sender
{
    [tableSource annull];

    NSTabViewItem *tabItem;
    tabItem = [tabView selectedTabViewItem];
    id tabViewId = [tabItem identifier];

    if ([tabViewId isEqual:@"insert"]) {
        [insertAtPosition setTextColor:[NSColor blackColor]];

    }else if([tabViewId isEqual:@"remove"])
    {
        [from setTextColor:[NSColor blackColor]];
        [to setTextColor:[NSColor blackColor]];
    }
    renamed = NO;
    [renameButton setEnabled:NO];
    [tabella reloadData];
}

/*###########################log section######################################*/
-(IBAction)showLogWindows:(id)sender{

    if ([logWindow isVisible]) {
        [logWindow setIsVisible:FALSE];
    }else {
        [logWindow setIsVisible:TRUE];
    }
}
-(void)addToLog:(NSString *)text
{
    NSString *textLog = [text stringByAppendingString:@"\n\r"];
    NSRange endRange;
    endRange.location = [[logField textStorage] length];
    endRange.length = 0;
    [logField replaceCharactersInRange:endRange withString:textLog];
    endRange.length = [textLog length];
    [logField scrollRangeToVisible:endRange];
}
/*#######################end log section######################################*/

/*######################editing actions#######################################*/

-(IBAction)finalRenaming:(id)sender
{
    if(KDEBUG)
        NSLog(@"renaming button pressed");
    //start the progression bar
    [progBar startAnimation:self];
    //count of the files really renamed
    int countRenamed = 0;
    //count of the renaming error
    int errRenamed = 0;
    //the result of rename()
    int renameResult;
    //the enumerator and the obj
    NSEnumerator *en = [tableSource objectEnumerator];
    id row;
    if(renamed)
    {
        while(row = [en nextObject])
        {
            renameResult = rename([[row objectAtIndex:0] fileSystemRepresentation], [[row objectAtIndex:1] fileSystemRepresentation]);
            if(renameResult == 0){
                    NSString *textLog = [NSString stringWithFormat:@"%@ renamed with\n %@", [row objectAtIndex:0],[row objectAtIndex:1]];
                    NSLog(textLog);
                    [self addToLog:textLog];
                    countRenamed++;
                }else {
                    NSString *textLog =[NSString stringWithFormat: @"Error in file renaming %@", [row objectAtIndex:0]];
                    NSLog(textLog);
                    [self addToLog:textLog];
                    errRenamed++;
            }
        }
        if(errRenamed >0){
            //open the panel alert
            int result;
            result = NSRunAlertPanel(@"Renaming error. Please check the log", @"Error!", @"Ok", NULL, NULL);
        }
        //print the result of renaming
        [notiField setStringValue:[NSString stringWithFormat:@"renamed %d/%d files, %d errors", countRenamed,[tableSource count],errRenamed]];
        //
        [tableSource reinitialize];
        [tabella reloadData];
        [renameButton setEnabled:NO];
        [annullButton setEnabled:NO];
        [progBar stopAnimation:self];
    }
}

- (void)textDidEndEditing:(NSNotification *)aNotification
{
    [progBar startAnimation:self];
    NSTabViewItem *tabItem;
    tabItem = [tabView selectedTabViewItem];
    id tabViewId = [tabItem identifier];

    if ([tabViewId isEqual:@"insert"]) {
        if(KDEBUG)
            NSLog(@"insert selected");
            if(insoverappPosition == 1)
            {
                if(KDEBUG)
                    NSLog(@"overwrite selected");
                tableSource = [renamer overwriteChar:tableSource insertText:[insertText stringValue] position:[insertAtPosition intValue] withExt:withExt];
            }else if(insoverappPosition == 0){
                if(KDEBUG)
                    NSLog(@"insert selected");
                tableSource = [renamer insertChar:tableSource insertText:[insertText stringValue] position:[insertAtPosition intValue] withExt:withExt];
            }else if(insoverappPosition == 2){
                if(KDEBUG)
                    NSLog(@"append selected");
                tableSource = [renamer appendChar:tableSource appendText:[insertText stringValue] withExt:withExt]; 
            }
    }else if ([tabViewId isEqual:@"remove"]) {
        if(KDEBUG)
            NSLog(@"remove selected");
        tableSource = [renamer removeChar:tableSource from:[from intValue] to:[to intValue] withExt:withExt];
    }else if([tabViewId isEqual:@"search"]){
        if(KDEBUG)
            NSLog(@"search selected");
        tableSource = [renamer searchAndReplace:tableSource string:[searchField stringValue] withString:[replaceField stringValue] withExt:withExt];
    }
    [progBar stopAnimation:self];
}

-(IBAction)upLowerCellClicked:(id)sender
{
    NSCell* cell;
    cell = [upper_lower selectedCell];
    int tag = [cell tag];

    if (tag == 0) {
        if(KDEBUG)
            NSLog(@"lowercase selected");
        tableSource = [renamer makeLowerCase:tableSource withExt:withExt];
        [renameButton setEnabled:YES];
        [annullButton setEnabled:YES];
        [tabella reloadData];
    }
    else if(tag == 1){
        if(KDEBUG)
            NSLog(@"uppercase selected");
        tableSource = [renamer makeUpperCase:tableSource withExt:withExt];
        [renameButton setEnabled:YES];
        [annullButton setEnabled:YES];
        [tabella reloadData];
    }
}

-(IBAction)insertOverwriteClicked:(id)sender
{
    if(KDEBUG)
        NSLog(@"insertOverwriteClicked");
    NSCell* cell;
    cell = [insert_overwrite selectedCell];
    int tag = [cell tag];

    if(tag == 0)
    {
        if(KDEBUG)
            NSLog(@"insert");
        [insertAtPosition setEnabled:YES];
        insoverappPosition = 0;
    }else if(tag==1){
        if(KDEBUG)
            NSLog(@"overwrite");
        [insertAtPosition setEnabled:YES];
        insoverappPosition = 1;
    }else if (tag==2) {
        if(KDEBUG)
            NSLog(@"append");
        [insertAtPosition setEnabled:NO];
        insoverappPosition = 2;
    }
}
/*################end editing actions#########################################*/


-(void)newUpdateIsOnline
{
    NSLog(@"newUpdateIsOnline");

    BOOL retval;
    retval = (NSAlertDefaultReturn == NSRunAlertPanel(@"Update Available", @"Update now or later", @"Update", @"Cancel", nil, nil));
    if(retval){
        if(KDEBUG)
            NSLog(@"update now");
        [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"http://www.hardboiled.it/software/rinominatore-upgrade.zip"]];
        //to edit
        //[[NSNotificationCenter defaultCenter] postNotificationName:@"openSheetNotification" object:self userInfo:nil];
    }else {
        if(KDEBUG)
            NSLog(@"cancel the update");
    }
    //release the updater. now is useless
    [updater release];

}

/*################nstableview delegates#######################################*/
- (int)numberOfRowsInTableView:(NSTableView *)aTableView
{
    return [tableSource count];
}

- (id)tableView:(NSTableView *)aTableView objectValueForTableColumn:(NSTableColumn *)aTableColumn row:(int)rowIndex 
{   
    if ([[aTableColumn identifier] isEqualToString: @"original_name"]) {
        id obj = [tableSource objectAtRow:rowIndex atIndex:0] ;
        return [obj lastPathComponent];
        //return theIcon;
    }else if([[aTableColumn identifier] isEqualToString: @"new_name"]){
        id obj = [tableSource objectAtRow:rowIndex atIndex:1] ;
        return [obj lastPathComponent];
    }
    return nil;
}


- (void)tableView:(NSTableView *)aTableView willDisplayCell:(id)cell forTableColumn:(NSTableColumn *)aTableColumn row:(int)rowIndex
{
    if(cell_with_icon)
    {
        if ( [[aTableColumn identifier] isEqualToString:@"original_name"] ){
            [((ImageAndTextCell*) cell) setImage:[tableSource objectAtRow:rowIndex atIndex:2]]; 
        }
    }

}
/* ###############end nstableview delegates #################################*/

/*############### nstoolbar delegates #######################################*/
- (NSArray *) toolbarAllowedItemIdentifiers: (NSToolbar *) toolbar
{
    return [NSArray arrayWithObjects:addFilesIdentifier, 
        removeFilesIdentifier,cleanAllIdentifier,
        NSToolbarFlexibleSpaceItemIdentifier, 
        NSToolbarSpaceItemIdentifier, 
        NSToolbarSeparatorItemIdentifier, nil];;
}
- (NSArray *) toolbarDefaultItemIdentifiers: (NSToolbar *)toolbar 
{
    return [NSArray arrayWithObjects:addFilesIdentifier, 
        removeFilesIdentifier,NSToolbarFlexibleSpaceItemIdentifier,cleanAllIdentifier,  nil];
}

- (NSToolbarItem *)toolbar:(NSToolbar *)toolbar itemForItemIdentifier:(NSString *)itemIdentifier willBeInsertedIntoToolbar:(BOOL)flag
{
    NSToolbarItem *toolbarItem = nil;

    if ([itemIdentifier isEqualTo:addFilesIdentifier]) {//button addfiles
        toolbarItem = [[NSToolbarItem alloc] initWithItemIdentifier:itemIdentifier];
        [toolbarItem setLabel:@"Add"];
        [toolbarItem setPaletteLabel:[toolbarItem label]];
        [toolbarItem setToolTip:@"Add"];
        [toolbarItem setImage:[NSImage imageNamed:@"add.icns"]];
        [toolbarItem setTarget:self];
        [toolbarItem setAction:@selector(addFiles:)];

    }else if ([itemIdentifier isEqualTo:removeFilesIdentifier]) {//button remove files
        toolbarItem = [[NSToolbarItem alloc] initWithItemIdentifier:itemIdentifier];
        [toolbarItem setLabel:@"Remove"];
        [toolbarItem setPaletteLabel:[toolbarItem label]];
        [toolbarItem setToolTip:@"Remove"];
        [toolbarItem setImage:[NSImage imageNamed:@"remove.icns"]];
        [toolbarItem setTarget:self];
        [toolbarItem setAction:@selector(removeFiles:)];

    }else if ([itemIdentifier isEqualTo:cleanAllIdentifier]) {//button clean
        toolbarItem = [[NSToolbarItem alloc] initWithItemIdentifier:itemIdentifier];
        [toolbarItem setLabel:@"Clean All"];
        [toolbarItem setPaletteLabel:[toolbarItem label]];
        [toolbarItem setToolTip:@"Clean the table"];
        [toolbarItem setImage:[NSImage imageNamed:@"cleanAll.icns"]];
        [toolbarItem setTarget:self];
        [toolbarItem setAction:@selector(clearTable:)];
    }
    return [toolbarItem autorelease];
}
/*###############end nstoolbar delegates #####################################*/

/*################drag'n drop  delegates #####################################*/
- (BOOL)tableView:(NSTableView *)tv writeRowsWithIndexes:(NSIndexSet *)rowIndexes toPasteboard:(NSPasteboard*)pboard {
    // Drag and drop support
     NSData *data = [NSKeyedArchiver archivedDataWithRootObject:rowIndexes];
     [pboard declareTypes:[NSArray arrayWithObject:NSFilenamesPboardType] owner:self];
     [pboard setData:data forType:NSFilenamesPboardType];
    return YES;
}

- (NSDragOperation)tableView:(NSTableView*)tv validateDrop:(id <NSDraggingInfo>)info proposedRow:(int)row proposedDropOperation:(NSTableViewDropOperation)op
{
    // Add code here to validate the drop
    if (KDEBUG)
    NSLog(@"validate Drop");
    return NSDragOperationEvery;
}

- (BOOL)tableView:(NSTableView*)tv acceptDrop:(id )info row:(int)row dropOperation:(NSTableViewDropOperation)op 
{
    if (KDEBUG)
        NSLog(@"acceptDrop");

    NSPasteboard *pboard = [info draggingPasteboard];
    if ( [[pboard types] containsObject:NSFilenamesPboardType] ) {
        NSArray *files = [pboard propertyListForType:NSFilenamesPboardType];
        [tableSource add:files];
    }
    [tabella reloadData];
    return YES;
}
/*################end drag'n drop  delegates ##################################*/


@end

委托是對象,而不是方法。 ControllerMain對象設置為其他對象的委托。 當另一個對象看到發生了告訴其重命名的條件時(無論是什么意思),它會按照[[self delegate] renamed] ,該操作調用ControllerMain方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM