Objective c 目标C中的代表
我试图探索Objective-C中的一些代码。我遇到了一个开源程序—批重命名程序。我查看了它的代码并添加了自己的实现。这段代码中有一件事我无法理解——我希望有人能帮助我。 问题是有一个重命名委托“-(void)renamed”,我不知道它是如何调用的。因此,我想知道程序如何知道何时调用/使用此委托。 代码如下:Objective c 目标C中的代表,objective-c,delegates,Objective C,Delegates,我试图探索Objective-C中的一些代码。我遇到了一个开源程序—批重命名程序。我查看了它的代码并添加了自己的实现。这段代码中有一件事我无法理解——我希望有人能帮助我。 问题是有一个重命名委托“-(void)renamed”,我不知道它是如何调用的。因此,我想知道程序如何知道何时调用/使用此委托。 代码如下: #import "ControllerMain.h" static NSString *addFilesIdentifier = @"addFiles_item"; static NS
#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.h”
静态NSString*AddFileIdentifier=@“addFiles\u项”;
静态NSString*RemoveFileIdentifier=@“removeFiles\u项”;
静态NSString*CleanalIdentifier=@“cleanAll_项”;
静态NSString*updateUrl=@”http://www.hardboiled.it/software/update.xml";
@实现控制器
-(id)init
{
self=[super init];
//初始化某个对象
tableSource=[[NSMutableArray alloc]init];
更新程序=[[STUpdateChecker alloc]init];
重命名器=[[streamer alloc]init];
//设置一些变量
withExt=NO;//对于在重命名中包含扩展名,默认为NO
重命名=否;//重命名预览后为是
内平均位置=0;
//设置NSControlTextDidChangeNotification的通知
NSNotificationCenter*nc=[NSNotificationCenter defaultCenter];
[nc addObserver:自选择器:@selector(textdidediting:)名称:@“NSControlTextDidChangeNotification”对象:nil];
回归自我;
}
-(无效)从NIB中唤醒
{
//设置代表
[tabella setDelegate:self];
[表源setDelegate:self];
[重命名器setDelegate:self];
[更新程序setDelegate:self];
//检查软件是否已更新
[updater checkUpdateWithUrl:[NSURL URLWithString:updateUrl]];
//拖放-设置拖动的类型
[tabella RegisterForDragedTypes:[NSArray arrayWithObjects:nsFileNamesPardType,nil]];
//工具栏配置
toolbar=[[NSToolbar alloc]initWithIdentifier:@“toolbar”];
[工具栏设置委托:自我];
//mainWindows属性
[主窗口中心];
[主窗口设置标题:@“MacxRename”];
[主窗口设置工具栏:工具栏];
//设置扩展复选框
[extSwitch设置状态:0];
//设置自定义单元格imageAndTextCell
ImageAndTextCell*ImageAndTextCell=nil;
NSTableColumn*tableColumn=nil;
tableColumn=[tabella tableColumnWithIdentifier:@“原始名称”];
imageAndTextCell=[[imageAndTextCell alloc]init]自动释放];
[图像和文本单元格设置可编辑:否];
[tableColumn setDataCell:imageAndTextCell];
//
//初始化空表的窗口
[自表资源集];
//释放工具栏
[工具栏释放];
}
-(无效)解除锁定
{
//全部释放
[tabella Unregistedraggedtypes];
[表源发布];
[重命名器释放];
[super dealoc];
}
-(BOOL)应用程序应在LastWindowClosed之后终止:(NSApplication*)发送方
{
//关闭应用程序
返回YES;
}
/*表源代表#################################*/
-(void)表资源列表
{
if(KDEBUG)
NSLog(@“表源为空”);
[上下设置启用:否];
[来自setEditable:否];
[要设置为可编辑:否];
[插入文本设置可编辑:否];
[插入位置设置可编辑:否];
[插入位置setIntValue:0];
[重命名按钮设置启用:否];
[环形按钮设置启用:否];
[搜索字段设置可编辑:否];
[替换字段设置可编辑:否];
}
-(void)表资源诱惑
{
if(KDEBUG)
NSLog(@“表源不为空”);
[上下设置启用:是];
[来自setEditable:是];
[要设置可编辑:是];
[插入文本设置可编辑:是];
[插入位置设置可编辑:是];
[搜索字段设置可编辑:是];
[replaceField setEditable:是];
}
-(void)表源IDChange
{
NSString*countString=[NSString stringWithFormat:@“%d个文件,[tableSource count]];
[设置字符串值的文件数:countString];
}
/*####################结束表源委托###############################*/
/*######################重命名代理#####################################*/
-(无效)重命名为
{
NSLog(@“重命名预览正常”);
NSTabViewItem*tabItem;
tabItem=[tabView selectedTabViewItem];
id tabViewId=[tabItem标识符];
如果([tabViewId isEqual:@“插入”]){
[插入位置setTextColor:[NSColor blackColor]];
}else if([tabViewId isEqual:@“删除”])
{
[来自setTextColor:[NSColor blackColor]];
[to setTextColor:[NSColor blackColor]];
}
重命名=是;
[重命名按钮设置启用:是];
[环形按钮设置启用:是];
}
-(无效)未重命名
{
重命名=否;
NSTabViewItem*tabItem;
tabItem=[tabView selectedTabViewItem];
id tabViewId=[tabItem标识符];
如果([tabViewId isEqual:@“插入”]){
[插入位置setTextColor:[NSColor redColor]];
}else if([tabViewId isEqual:@“删除”])
{
[来自setTextColor:[NSColor redColor]];
[to setTextColor:[NSColor redColor]];
}
NSLog(@“预览委托中的异常”);
[重命名按钮设置启用:否];
}
/*结束重命名者代表##################################*/
//使文件扩展名可编辑
-(iAction)makeExtEditable:(id)发件人
{
if(KDEBUG)
NSLog(@“makeExtEditable操作”);
如果([发送方状态]==0){
withExt=否;
}else if([发送方状态]==1){
withExt=是;
}
}
//将文件添加到表中
-(iAction)添加文件:(id)发件人
{
//启动进度条
[progBar startAnimation:self];
int结果;
NSOpenPanel*oPanel=[NSOpenPanel openPanel];
[oPanel setCanChooseFiles:是];
[oPanel setAllowsMultipleSelection:是];
[蛋白石:否];
结果=[oPanel runModalForTypes:nil];
如果(结果==NSOKButton){
NSArray*filesToOpen=[oPanel文件名];
[表源添加:filesToOpen];
[tabella重新加载数据];
}
//停止p