如何在应用程序中创建Finder别名?

时间:2009-12-18 13:14:42

标签: objective-c cocoa finder

从Cocoa应用程序创建Finder别名所需的代码是什么? OS X 10.5,10.6和10.7之间的代码有什么不同吗?

4 个答案:

答案 0 :(得分:5)

自OS X 10.6起,您可以使用NSUrl的{​​{1}}方法

来自documentation

  

在指定位置的磁盘上创建别名文件   书签数据。

示例代码:

writeBookmarkData:toURL:options:error:

但是,以这种方式创建的别名不能向后兼容早期的OS X版本(10.6之前版本)

答案 1 :(得分:4)

看看How to Create an Alias Programmatically

- (void)makeAliasToFolder:(NSString *)destFolder inFolder:(NSString *)parentFolder withName:(NSString *)name
{
    // Create a resource file for the alias.
    FSRef parentRef;
    CFURLGetFSRef((CFURLRef)[NSURL fileURLWithPath:parentFolder], &parentRef);
    HFSUniStr255 aliasName;
    FSGetHFSUniStrFromString((CFStringRef)name, &aliasName);
    FSRef aliasRef;
    FSCreateResFile(&parentRef, aliasName.length, aliasName.unicode, 0, NULL, &aliasRef, NULL);

    // Construct alias data to write to resource fork.
    FSRef targetRef;
    CFURLGetFSRef((CFURLRef)[NSURL fileURLWithPath:destFolder], &targetRef);
    AliasHandle aliasHandle = NULL;
    FSNewAlias(NULL, &targetRef, &aliasHandle);

    // Add the alias data to the resource fork and close it.
    ResFileRefNum fileReference = FSOpenResFile(&aliasRef, fsRdWrPerm);
    UseResFile(fileReference);
    AddResource((Handle)aliasHandle, 'alis', 0, NULL);
    CloseResFile(fileReference);

    // Update finder info.
    FSCatalogInfo catalogInfo;
    FSGetCatalogInfo(&aliasRef, kFSCatInfoFinderInfo, &catalogInfo, NULL, NULL, NULL);
    FileInfo *theFileInfo = (FileInfo*)(&catalogInfo.finderInfo);
    theFileInfo->finderFlags |= kIsAlias; // Set the alias bit.
    theFileInfo->finderFlags &= ~kHasBeenInited; // Clear the inited bit to tell Finder to recheck the file.
    theFileInfo->fileType = kContainerFolderAliasType;
    FSSetCatalogInfo(&aliasRef, kFSCatInfoFinderInfo, &catalogInfo);
}

你也可以使用applescript

osascript -e 'tell application "Finder" to make alias file to POSIX file "/Applications/myapp.app" at POSIX file "/Applications/"'

答案 2 :(得分:0)

使用Swift3在指定位置的磁盘上创建具有指定书签数据的别名文件。

示例代码:

let url = URL(string: "originalURL")
let aliasUrl = URL(string: "aliasURL")
do{
      let data = try url.bookmarkData(options: .suitableForBookmarkFile, includingResourceValuesForKeys: nil, relativeTo: nil)
            try URL.writeBookmarkData(data, to: aliasUrl)
  }catch{}

答案 3 :(得分:-1)

你想要-[NSFileManager linkItemAtPath:toPath:error:]。 AFIK,它及其相关方法是所有版本的首选方法。

相关问题