Objective c 使用Cocoa为文件夹创建图标

Objective c 使用Cocoa为文件夹创建图标,objective-c,cocoa,macos,icons,Objective C,Cocoa,Macos,Icons,在我的Mac OS应用程序中,我会提示用户创建一个新文件夹。我想在创建此文件夹时使用Cocoa将图标应用于此文件夹。目前,要创建文件夹,我使用以下代码: - (IBAction)browseFiles:(id)sender { NSOpenPanel *oPanel = [[NSOpenPanel openPanel] retain]; [oPanel setCanChooseDirectories:YES]; [oPanel setCanChooseFiles:NO];

在我的Mac OS应用程序中,我会提示用户创建一个新文件夹。我想在创建此文件夹时使用Cocoa将图标应用于此文件夹。目前,要创建文件夹,我使用以下代码:

- (IBAction)browseFiles:(id)sender
{
    NSOpenPanel *oPanel = [[NSOpenPanel openPanel] retain];
    [oPanel setCanChooseDirectories:YES];
    [oPanel setCanChooseFiles:NO];
    [oPanel setDelegate:self];
    [oPanel setCanCreateDirectories:YES];
    [oPanel beginSheetForDirectory:NSHomeDirectory()
                              file:nil
                             types:nil
                    modalForWindow:nil
                     modalDelegate:self
                    didEndSelector:@selector(filePanelDidEnd:
                                             returnCode:
                                             contextInfo:)
                       contextInfo:nil];
}
选择目录后,用户单击确认按钮,该按钮使用以下方法调用函数:

bool set = [[NSWorkspace sharedWorkspace] setIcon:[NSImage imageNamed:@"icon.icns"] forFile:path options:NSExcludeQuickDrawElementsIconCreationOption]; 
虽然上面的代码返回“是”,但图标未成功应用于文件夹。我的代码是否有问题


谢谢。

NSWorkspace方法在这里非常有效。可能您的图标格式无效?
我尝试了
setIcon:
使用Finder图标:

- (IBAction)setFolderIcon:(id)sender
{
    NSOpenPanel* openPanel = [NSOpenPanel openPanel];
    [openPanel setCanChooseFiles:NO];
    [openPanel setCanChooseDirectories:YES];
    switch([openPanel runModal])
    {
        case NSFileHandlingPanelOKButton:
        {
            NSURL* directoryURL = [openPanel directoryURL];
            NSImage* iconImage = [[NSImage alloc] initWithContentsOfFile:@"/System/Library/CoreServices/Finder.app/Contents/Resources/Finder.icns"];
            BOOL didSetIcon = [[NSWorkspace sharedWorkspace] setIcon:iconImage forFile:[directoryURL path] options:0];
            NSLog(@"%d", didSetIcon);
            [iconImage release];
        }
        case NSFileHandlingPanelCancelButton:
        {
            return;
        }
    }
}

请尝试在此处查看:。我想你可能需要一个PNG文件作为图标。这个问题是关于如何通过编程设置Mac OS X图标的。你链接的答案描述了iPhone图标应该具有的格式。不要忘记发布NSImage实例(假设你没有使用GC)。谢谢Peter。更新答案。